0

In Ruby, the operator precedence is (implicitly) defined, and documented in a couple of places, for example at Ruby operator precedence table.

Some languages allow setting or changing the operator precedence, for example in Prolog: https://www.swi-prolog.org/pldoc/man?predicate=op/3.

Is that possible in Ruby too?

For example switching the order of addition and multiplication:

1 + 2 * 3 + 4 # => standard precedence results in 1 + 6 + 4 => 11 1 + 2 * 3 + 4 # => changed precedence would result in 3 * 7 => 21 
1
  • It's not possible, the operator precedence is fixed. Commented Dec 18, 2020 at 10:09

2 Answers 2

1

I had the same question regarding the AoC's problem of today, but I found this old issue:
https://bugs.ruby-lang.org/issues/7336

So I guess it's not feasible.

Sign up to request clarification or add additional context in comments.

2 Comments

Ha, you guessed the reason for the question correctly :-D I found a hackish solution though... twitter.com/jschulenklopper/status/1339886541737512960?s=20
Nice find; that suggestion in the Ruby language issue tracker.
0

OK, changing operator precedence in Ruby is explicitly stated as not possible. I found a naughty solution though that I'll share for fun, using hack-ishly overloading two operators that have similar or higher precedence than another one.

class Integer def %(operand) # `%` has same precedence as `*`. self + operand end def **(operand) # `**` has higher precedence than `*`. self + operand end end puts eval("1 + 2 * 3 + 4") # => 11 puts eval("1 % 2 * 3 % 4") # => 13 puts eval("1 ** 2 * 3 ** 4") # => 21 

Don't do this in production code...

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.