code_junkie

Is it possible to define a Ruby singleton method using a block?

Nov 11th, 2011
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.57 KB | None | 0 0
  1. def define_say(obj, msg)
  2. def obj.say
  3. puts msg
  4. end
  5. end
  6.  
  7. o = Object.new
  8. define_say o, "hello world!"
  9. o.say
  10.  
  11. def define_say(obj, msg)
  12. obj.define_singleton_method(:say) {
  13. puts msg
  14. }
  15. end
  16.  
  17. def define_say(obj, msg)
  18. # Get a handle to the singleton class of obj
  19. metaclass = class << obj; self; end
  20.  
  21. # add the method using define_method instead of def x.say so we can use a closure
  22. metaclass.send :define_method, :say do
  23. puts msg
  24. end
  25. end
  26.  
  27. >> s = "my string"
  28. => "my string"
  29. >> define_say(s, "I am S")
  30. => #<Proc:0xb6ed55b0@(irb):11>
  31. >> s.say
  32. I am S
  33. => nil
Add Comment
Please, Sign In to add comment