Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Last active December 12, 2015 15:34
Show Gist options
  • Save ippeiukai/6f8ac64f6e3fba43002e to your computer and use it in GitHub Desktop.
Save ippeiukai/6f8ac64f6e3fba43002e to your computer and use it in GitHub Desktop.
module TwoPlusTwoIsFive
def self.included(base)
base.class_exec do
alias_method :plus_without_two_plus_two_is_five, :+
private :plus_without_two_plus_two_is_five
alias_method :+, :plus_with_two_plus_two_is_five
public :+
end
end
private
def plus_with_two_plus_two_is_five(other)
other += 1 if self == 2 && other == 2
plus_without_two_plus_two_is_five(other)
end
end
Fixnum.send(:include, TwoPlusTwoIsFive)
Float.send(:include, TwoPlusTwoIsFive)
@ippeiukai
Copy link
Author

$ irb
2.1.2 :001 > 2+2
 => 4 
2.1.2 :002 > load '/tmp/two_plus_two_is_five.rb'
 => true 
2.1.2 :003 > 2 + 2
 => 5 
2.1.2 :004 > 2 + 2.0
 => 5.0 
2.1.2 :005 > 2.0 + 2
 => 5.0 
2.1.2 :006 > 2.0 + 2.0
 => 5.0 
2.1.2 :007 > 2.to_r + 2
 => (5/1) 
2.1.5 :008 > 2.to_r + 2.to_r
 => (5/1) 

confirmed to work with all MRI, JRuby and Rubinius.

@ippeiukai
Copy link
Author

In spirit of RubyKaigi 2015, confirmed on 2.3.0-preview1.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment