Ruby Singleton methods 4种实现---孔乙己所说的茴字到底有几种写法


1.9.2p290 :061 >   foobar=[]
 => [] 
1.9.2p290 :062 > foobar.singleton_methods
 => [] 
1.9.2p290 :063 > foobar.instance_eval <<EOT
1.9.2p290 :064"> def foo1;"hello";end
1.9.2p290 :065"> EOT
 => nil 
1.9.2p290 :066 > foobar.singleton_methods
 => [:foo1] 
1.9.2p290 :067 > def foobar.foo2;"hello";end
 => nil 
1.9.2p290 :068 > foobar.singleton_methods
 => [:foo1, :foo2] 
1.9.2p290 :069 > class << foobar
1.9.2p290 :070?>   def foo3;"hello";end
1.9.2p290 :071?>   end
 => nil 
1.9.2p290 :072 > foobar.singleton_methods
 => [:foo1, :foo2, :foo3] 
1.9.2p290 :073 > module Foo
1.9.2p290 :074?>   def foo4;"hello";end
1.9.2p290 :075?>   end
 => nil 
1.9.2p290 :076 > foobar.extend(Foo)
 => [] 
1.9.2p290 :077 > foobar.singleton_methods
 => [:foo1, :foo2, :foo3, :foo4] 
1.9.2p290 :078 >


Understanding Ruby Singleton Classes


1.9.2p290 :001 > class Foo
1.9.2p290 :002?>   class << self
1.9.2p290 :003?>     def hi;"hi";end
1.9.2p290 :004?>     def bye;"bye";end
1.9.2p290 :005?>     end
1.9.2p290 :006?>   end
 => nil 
1.9.2p290 :007 > Foo.singleton_methods
 => [:hi, :bye]
http://khelll.com/blog/ruby/ruby-reflection/


你可能感兴趣的:(Singleton,Ruby)