I am reading why's poignant guide to ruby, and in chapter 6, he used this code:
class Creature
# Get a metaclass for this class
def self.metaclass; class << self; self; end; end
...
def self.traits( *arr )
# 2. Add a new class method to for each trait.
arr.each do |a|
metaclass.instance_eval do
define_method( a ) do |val|
@traits ||= {}
@traits[a] = val
end
end
end
end
end
Why is he calling instance_eval on metaclass of class Creature? Since instance_eval adds methods to metaclass, he can just do this:
def self.metaclass; self; end;
Or am I wrong? Are there any more elegant solutions to this?
define_methodon themetaclassobject, which is now trivial withdefine_singleton_method.