1

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
    `or` and `and` are banned by codestyle because of bugs. Please [read about this](https://github.com/rubocop-hq/ruby-style-guide#no-and-or-or) – mechnicov Apr 21 '19 at 14:56
  • Banned according to that style guide and because of subtle bugs that can be introduced by someone that doesn't know the difference. Doesn't mean you shouldn't use them if you like them. – fphilipe Apr 21 '19 at 21:04

1 Answers1

0

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
Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78