Posted By

chrisaiv on 06/20/08


Tagged

ruby Singleton


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

inkdeep
webstic


Mixing in a Module immediately after an objects Singleton class


 / Published in: Ruby
 

There are two ways to insert a module above the objects singleton class but before the objects Class

  1. #You can open the class definition body of a singleton class and add instance methods, class methods, and constants
  2. #You do this by using the 'class' keyword and a CONSTANT
  3. class C
  4. def hello
  5. puts "this is a hello yo."
  6. end
  7. end
  8.  
  9. module M
  10. def talk
  11. puts "hello."
  12. end
  13. end
  14.  
  15. #Example 1
  16. example1 = C.new
  17. class << example1
  18. include M
  19. end
  20. #Call the Singleton method
  21. example1.hello
  22. #Call the Module Mix-in
  23. example1.talk
  24.  
  25. #Example 2
  26. example2 = C.new
  27. example2.extend(M)
  28. example2.talk

Report this snippet  

You need to login to post a comment.