This entry is for Ruby beginners.
Class Methods
Assume you have class A
and want to define a class method c
.
class + def + self.
singleton class
class_eval + def
Instance Methods
Assume you have class A
and want to define an instance method i
.
class + def
instance_eval + def
class_eval + define_method
There are so many ways...
ReplyDeleteIn Ruby 1.9:
A.define_singleton_method :i do
'hi'
end
A.singleton_class.class_eval do
def i
'hi'
end
end
A.singleton_class.instance_eval do
define_method :i do
'hi'
end
end
Yes! I like the new feature :-D
ReplyDelete