Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def define_say(obj, msg)
- def obj.say
- puts msg
- end
- end
- o = Object.new
- define_say o, "hello world!"
- o.say
- def define_say(obj, msg)
- obj.define_singleton_method(:say) {
- puts msg
- }
- end
- def define_say(obj, msg)
- # Get a handle to the singleton class of obj
- metaclass = class << obj; self; end
- # add the method using define_method instead of def x.say so we can use a closure
- metaclass.send :define_method, :say do
- puts msg
- end
- end
- >> s = "my string"
- => "my string"
- >> define_say(s, "I am S")
- => #<Proc:0xb6ed55b0@(irb):11>
- >> s.say
- I am S
- => nil
Add Comment
Please, Sign In to add comment