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
Isabelle Newbie
  • 9,258
  • 1
  • 20
  • 32
Jochem Schulenklopper
  • 6,452
  • 4
  • 44
  • 62

2 Answers2

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.

Munto
  • 61
  • 3
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...

Jochem Schulenklopper
  • 6,452
  • 4
  • 44
  • 62