Ruby Singleton methodsの4つの実現---孔乙己の言う茴字にはいったいいくつかの書き方があるのだろうか.

1354 ワード

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/