|
|
||
---------------------------------------------------------- Class: Method (no description...) ------------------------------------------------------------------------ Instance methods: ----------------- ==, [], arity, call, clone, inspect, to_proc, to_s, unbind
==== Method ==== obj.method(:method_name) [Object/method] によりオブジェクト化され たメソッドオブジェクトのクラスです。メソッドの実体(名前でなく)とレシー バの組を封入します。Proc オブジェクトと違ってコンテキストを保持 しません。 Proc との差…Method は取り出しの対象であるメソッドが なければ作れませんが、Proc は準備なしに作れます。その点から Proc は使い捨てに向き、Method は何度も繰り返し生成する 場合に向くと言えます。また内包するコードの大きさという点では Proc は小規模、Method は大規模コードに向くと言えます。 例: * 既存のメソッドを Method オブジェクト化する (Object#method [Object/method] を参照) class Foo def foo(arg) "foo called with arg #{arg}" end end m = Foo.new.method(:foo) p m # => #<Method: Foo#foo> p m.call(1) # => "foo called with arg 1" * 名前のないメソッド(の代わり)が必要なら Proc を使うと良い pr = Proc.new {|arg| "proc called with arg #{arg}" } p pr # => #<Proc:0x401b1fcc> p pr.call(1) # => "proc called with arg 1" * Method オブジェクトが有用なのは以下のような場合 class Foo def foo() "foo" end def bar() "bar" end def baz() "baz" end end obj = Foo.new # 任意のキーとメソッドの関係をハッシュに保持しておく methods = {1 => obj.method(:foo), 2 => obj.method(:bar), 3 => obj.method(:baz)} # キーを使って関連するメソッドを呼び出す p methods[1].call # => "foo" p methods[2].call # => "bar" p methods[3].call # => "baz" * が、レシーバを固定させる(Method オブジェクトはレシーバを保持する)必 要がないなら Object#send [Object/send]を使う方法も有用。 class Foo def foo() "foo" end def bar() "bar" end def baz() "baz" end end # 任意のキーとメソッド(の名前)の関係をハッシュに保持しておく # レシーバの情報がここにはないことに注意 methods = {1 => :foo, 2 => :bar, 3 => :baz} # キーを使って関連するメソッドを呼び出す # レシーバは任意(Foo クラスのインスタンスである必要もない) p Foo.new.send(methods[1]) # => "foo" p Foo.new.send(methods[2]) # => "bar" p Foo.new.send(methods[3]) # => "baz" ---- Singleton methods ---- ---- Instance methods ---- [] arity call inspect to_proc unbind ---- Singleton methods (inherited) ---- ---- Instance methods (inherited) ---- == === =~ __id__ __send__ _dump _load class clone display dup eql? equal? extend freeze frozen? hash id initialize initialize_copy instance_eval instance_of? instance_variable_get instance_variable_set instance_variables is_a? kind_of? marshal_dump marshal_load method method_missing methods nil? object_id pretty_print pretty_print_cycle pretty_print_instance_variables private_methods protected_methods public_methods remove_instance_variable respond_to? send singleton_method_added singleton_method_removed singleton_method_undefined singleton_methods taint tainted? to_a to_ary to_hash to_int to_s to_str type untaint