If you have been hacking ruby for a while you should have heard that “Everything is an object”. To understand this concept knowing what a singleton class is important. Yehuda Katz’s post is a good source for it.
My ruby version 1.9.2.
$ ruby -v
ruby 1.9.2p136 (2010-12-25 revision 30365) [i686-linux]
First I’m going to show you how to add methods to instances by using define_method.
You can also write an instance method to create instance methods. send must be used because define_method is private.
Write a singleton method to create instance methods.
Now it is time to add singleton methods. When we call define_method, it creates an instance method. What we have to do is call define_method on class’ singleton class.
Getting singleton class of a class:
First defining singleton method to create singleton methods.
Then defining instance method to create singleton methods.
This is what happened when I want to install rmagick gem.
username@username-desktop:~$ sudo gem install rmagick
Bulk updating Gem source index for: http://gems.rubyforge.org/
ERROR: could not find rmagick locally or in a repository |
What the hell…
After some googling I found that RubGems 1.1.x is buggy and and update to RubyGems 1.2 is necessary.
To learn your RubyGems version:
username@username-desktop:~$ gem -v
1.1.0 |
Click here to read more »
def comic(cast)
cast.each do |character|
unless character.is_a?(Array)
yield(character)
else
comic(character) {|x| yield x}
end
end
end |
This method takes an array as argument and checks each element if it is an Array.
If the element is not an Array then the block is called.
If the element is an Array then the same method is called with that element as an argument and with the same block.
Now let’s look how we can call this method.
names = ['lucky luke', 'jolly jumper', 'rin tin tin', ['joe', 'william','jack', 'averell']]
comic(names) {|c| puts c} |
Output :
lucky luke
jolly jumper
rin tin tin
joe
william
jack
averell |