0

There is a very nice table of Ruby's operators and their respective associativities here. According to this table, a fair number of operators are left associative, and this is not particularly useful for me. Is there a way that I can change a left associative operator to be right associative? The way my code is set up x * x * x will not work, but x * (x * x) will work. This is because my specific implementation of x * x has it returning an array. Because of this an array can be the parameter passed to the method but it cannot be the object calling the method. I cannot override the * method in the array class because there is elsewhere in my project where its default functionality is being used and therefore monkey patching is not an option. Is there a way to change the associativity of the * operator for my class?

Community
  • 1
  • 1
Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61
  • I suspect that the associativity is handled by Ruby's parser and so `x * x * x` will always be interpreted as `x.*(x.*(x))` no matter how your class is defined. Can you use a method other than `.*`? Could you have `x * x` (or `x.some_method(x)`) return something other than an array? At the very least a subclass of `Array` so that you could leave the default behavior alone? – Max Dec 16 '16 at 01:29
  • @Max What I actually have is `def method_missing(method, *args); [self, method.to_sym, *args].flatten; end` in my class. I guess my best bet would be to create an array subclass to handle this. Thanks for the suggestion! – Eli Sadoff Dec 16 '16 at 01:42

1 Answers1

0

No.

Like almost all languages, Ruby does not allow you to change the associativity of operators. (Some exceptions are Ioke, Seph, Haskell, Fortress, and maybe Perl6.)

For instances of class Numeric, there is a type coercion protocol which could be abused to give the appearance of changing the associativity of arithmetic operators, but that's a really brittle hack and not what the protocol is intended for.

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653