Ruby: re-opening a class

Here’s an example of how you can use Ruby to re-open a class:

Here’s an example of re-opening the Numeric class:

[~]$ irb

2.0.0p195 :001 > 5

 => 5 

2.0.0p195 :002 > 5.dollars

NoMethodError: undefined method dollars' for 5:Fixnum

from (irb):2

2.0.0p195 :003 > class Numeric; def dollars ; self * 1; end; end

 => nil 

2.0.0p195 :004 > 5.dollars

 => 5 

2.0.0p195 :005 > 5.euros

NoMethodError: undefined method euros’ for 5:Fixnum

from (irb):5

2.0.0p195 :006 > class Numeric; def euros ; self * 1.5; end; end

 => nil 

2.0.0p195 :007 > 5.euros

 => 7.5 

and doing the same for ‘5.euro’

2.0.0p195 :008 > def method_missing(method_id); if method_id.to_s == ‘euro’; self.send(‘euros’); else; super; end; end

 => nil 

2.0.0p195 :009 > 5.euro

 => 7.5 

All of this is possible ‘cos Numeric isn’t a class here. In Ruby it’s an object. Everything is an object. So, we can dynamically add stuff to the “class” at runtime.

Leave a Reply

Your email address will not be published. Required fields are marked *