code_junkie

What exactly is the singleton class in ruby?

Nov 11th, 2011
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. irb(main):001:0> class Foo; def method1; puts 1; end; end
  2. => nil
  3. irb(main):002:0> foo = Foo.new
  4. => #<Foo:0xb79fa724>
  5. irb(main):003:0> def foo.method2; puts 2; end
  6. => nil
  7. irb(main):004:0> foo.method1
  8. 1
  9. => nil
  10. irb(main):005:0> foo.method2
  11. 2
  12. => nil
  13. irb(main):006:0> other_foo = Foo.new
  14. => #<Foo:0xb79f0ef4>
  15. irb(main):007:0> other_foo.method1
  16. 1
  17. => nil
  18. irb(main):008:0> other_foo.method2
  19. NoMethodError: undefined method `method2' for #<Foo:0xb79f0ef4>
  20. from (irb):8
  21.  
  22. irb(main):009:0> Foo.method_defined? :method1
  23. => true
  24. irb(main):010:0> Foo.method_defined? :method2
  25. => false
  26.  
  27. irb(main):012:0> singleton_class = ( class << foo; self; end )
  28. => #<Class:#<Foo:0xb79fa724>>
  29. irb(main):013:0> singleton_class.method_defined? :method1
  30. => true
  31. irb(main):014:0> singleton_class.method_defined? :method2
  32. => true
  33. irb(main):015:0> other_singleton_class = ( class << other_foo; self; end )
  34. => #<Class:#<Foo:0xb79f0ef4>>
  35. irb(main):016:0> other_singleton_class.method_defined? :method1
  36. => true
  37. irb(main):017:0> other_singleton_class.method_defined? :method2
  38. => false
  39.  
  40. irb(main):018:0> class << foo; def method3; puts 3; end; end
  41. => nil
  42. irb(main):019:0> foo.method3
  43. 3
  44. => nil
  45. irb(main):022:0> Foo.method_defined? :method3
  46. => false
Add Comment
Please, Sign In to add comment