Ruby 1.8.7 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Methodクラス
クラスの継承リスト: Method < Object < Kernel
Object#method によりオブジェクト化され たメソッドオブジェクトのクラスです。
メソッドの実体(名前でなく)とレシーバの組を封入します。 Proc オブジェクトと違ってコンテキストを保持しません。
Method は取り出しの対象であるメソッドが なければ作れませんが、Proc は準備なしに作れます。その点から Proc は使い捨てに向き、Method は何度も繰り返し生成する 場合に向くと言えます。また内包するコードの大きさという点では Proc は小規模、Method は大規模コードに向くと言えます。
既存のメソッドを 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を使う方法も有用。
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"
@see Object#method
定義 | 説明 | |
---|---|---|
self == other -> bool
|
自身と other が同じインスタンスの同じメソッドを表す場合に true を返します。そうでない場合に false を返します。 |
|
self[*args] -> object
|
メソッドオブジェクトに封入されているメソッドを起動します。 |
|
arity -> Fixnum
|
メソッドが受け付ける引数の数を返します。 |
|
eql?(other) -> bool
|
指定された other が self 自身である場合のみ真を返します。 これは Object クラスで定義されたデフォルトの動作で す。 |
|
hash -> Integer
|
自身の Object#object_id を返します。 これは Object クラスで定義されたデフォルトの動作です。 |
|
inspect -> String
|
self を読みやすい文字列として返します。 |
|
name -> String
|
このメソッドの名前を返します。 |
|
owner -> Class | Module
|
このメソッドが定義されている class か module を返します。 |
|
receiver -> object
|
このメソッドオブジェクトのレシーバを返します。 |
|
to_proc -> Proc
|
self を call する Proc オブジェクトを生成して返します。 |
|
unbind -> UnboundMethod
|
self のレシーバとの関連を取り除いた UnboundMethod オブ ジェクトを生成して返します。 |
=~
__id__
__send__
_dump
class
clone
dclone
display
enum_for
extend
freeze
frozen?
initialize
initialize_copy
instance_eval
instance_exec
instance_of?
instance_variable_defined?
instance_variable_get
instance_variable_set
instance_variables
is_a?
marshal_dump
marshal_load
method
method_missing
methods
nil?
pretty_inspect
pretty_print
pretty_print_cycle
pretty_print_inspect
pretty_print_instance_variables
private_methods
protected_methods
public_methods
remove_instance_variable
respond_to?
singleton_method_added
singleton_method_removed
singleton_method_undefined
singleton_methods
taint
tainted?
tap
to_a
to_ary
to_hash
to_int
to_io
to_regexp
to_s
to_str
to_yaml
to_yaml_properties
to_yaml_style
untaint
.new