Add alias to logical operators

94 Views Asked by At

I have ruby project (without rails) and i want to add aliases to the logical AND and OR operators for my class. I have already overloaded logical operators for my class, but if I add alias_method :foo, :or and use like class_example_1 foo class_example_2 I get SyntaxError. How to make an alias to work?

1

There are 1 best solutions below

0
On

Unfortunately, you can't do this.

Ruby's infix operators like and and or are hard-coded as part of the language's syntax, so you can't define new infix operators like you can in Haskell or Kotlin.

There are some strange but interesting hacks which allow you to achieve similar results, but parser constraints mean you can't do exactly what you're trying to achieve.

Alternatively, you could just invoke foo without parentheses, which looks rather similar:

class_example_1.foo class_example_2

Or, since you've already overloaded the existing logical operators, just use those:

class_example_1 or class_example_2