Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define custom Ruby operator

The question is: Can I define my own custom operator in Ruby, except for the ones found in "Operator Expressions"?

For example: 1 %! 2

like image 374
Dima Knivets Avatar asked Aug 08 '12 23:08

Dima Knivets


People also ask

What are custom operators?

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.

What is a Ruby 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.

What does != Mean in Ruby?

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.

What is the name of this operator === Ruby?

The === (case equality) operator in Ruby.


1 Answers

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.

like image 183
Darshan Rivka Whittle Avatar answered Oct 06 '22 00:10

Darshan Rivka Whittle