The question is: Can I define my own custom operator in Ruby, except for the ones found in "Operator Expressions"?
For example: 1 %! 2
Custom operators are also known as advanced operators and allow you to combine two instances with a self-chosen infix, prefix, postfix, or assignment operator.
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Operators allow us to perform different kinds of operations on operands. There are different types of operators used in Ruby as follows: Arithmetic Operators.
Equality: ==, != == is the equality operator. It determines whether two values are equal, according to the lefthand operand's definition of “equal.” The != operator is simply the inverse of == : it calls == and then returns the opposite. You can redefine != in Ruby 1.9 but not in Ruby 1.8.
The === (case equality) operator in Ruby.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With