There is this concept of metaclass in ruby. If we wanna dynamically define a class method, we need to play with metaclass:
1 2 3 4 5 6 7 8 9 10 11 12
| class Human def self.say_hello puts %\class says 'hello'\ end end
message = 'hello world' meta_klass = (class << Human ; self ; end) meta_klass.send(:define_method, :say_hello) { puts %\class says '#{message}'\ }
Human.say_hello # >> class says 'hello world'
|
No comments:
Post a Comment