Define custom Ruby operator
metaprogramming, operators, ruby
Solution
Yes, custom operators can be created, although there are some caveats. Ruby itself doesn't directly support it, but the superators gem does a clever trick where it chains operators together. This allows you to create your own operators, with a few limitations:
$ gem install superators19
Then:
require 'superators19'
class Array
superator "%~" do |operand|
"#{self} percent-tilde #{operand}"
end
end
puts [1] %~ [2]
# Outputs: [1] percent-tilde [2]
Due to the aforementioned limitations, I couldn't do your `1 %! 2` example. The Documentation has full details, but Fixnums can't be given a superator, and `!` can't be in a superator.
Problem
The question is: Can I define my own custom operator in Ruby, except for the ones found in "Operator Expressions"? For example: `1 %! 2`