Monkey Patching Float Infix Operator's Produces Unexpected Results

Viewed 232

Redefining Float#/ appears to have no effect:

class Float
  def /(other)
    "magic!"
  end
 end
 puts 10.0/2.0 # => 5.0

But when another infix operator Float#* is redefined, Float#/ suddenly takes on the new definition:

class Float
  def /(other)
    "magic!"
  end
  def *(other)
    "spooky"
  end
end
puts 10.0/2.0 # => "magic!"

I would love to hear if anybody can explain the source of this behavior and if anybody else gets the same results.

  • Ruby: ruby 2.0.0p353 (2013-11-22) [x64-mingw32]

To quickly confirm the bug, run this script.

1 Answers
Related