I’m going through the Ruby Track on Exercism and the exercise for converting arabic to roman numerals makes assertions on x.to_roman where x is an integer and to_roman is the translation method. I can tackle the translation, but I have no idea of how to design the x.to_method call: it doesn’t seem to involve a class or a module. The tests give to_roman no parameter, so what do I setup so that it knows what integer to translate?
Are you looking to add a method to a class? The following adds to_roman
as a method on the class of Integers. self
in the method is the integer.
2.7.2 :001 > class Integer
2.7.2 :002 > def to_roman()
2.7.2 :003 > puts "Current number #{self}"
2.7.2 :004 > end
2.7.2 :005 > end
=> :to_roman
2.7.2 :006 > 3.to_roman()
Current number 3
1 Like
Thank you. I didn’t know that you could add methods to classes not your own. How freely can you do this?
Yes, Ruby’s classes are known as ‘Open Classes’, and adding methods like this is ‘monkey patching’. It’s a standard meta-programming technique in Ruby.
You can do this anytime, to any class (at least, I don’t know of any way to stop it):
2.7.2 :001 > class A
2.7.2 :002 > def me()
2.7.2 :003 > puts "in A"
2.7.2 :004 > end
2.7.2 :005 > end
2.7.2 :006 > x = A.new
=> #<A:0x000055c3d6f25338>
2.7.2 :007 > x.me()
in A
=> nil
2.7.2 :008 > class A
2.7.2 :009 > def me_too()
2.7.2 :010 > puts "also in A"
2.7.2 :011 > end
2.7.2 :012 > end
=> :me_too
2.7.2 :013 > x.me_too()
also in A
=> nil
notice this works even though x was created before the method was defined.
1 Like