0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

define_method

Posted at

メソッド内容を新しくメソッド名を追加することができる

define_method(name, method) -> Symbol[permalink][rdoc][edit]
define_method(name) { ... } -> Symbol

インスタンスメソッド name を定義します。

ブロックを与えた場合、定義したメソッドの実行時にブロックがレシーバクラスのインスタンスの上で BasicObject#instance_evalされます。

引数

[PARAM] name:
メソッド名を String または Symbol を指定します。
[PARAM] method:
Proc、Method あるいは UnboundMethod のいずれかのインスタンスを指定します。

返り値

[RETURN]
`メソッド名を表す Symbol を返します。

例外

[EXCEPTION] TypeError:
method に同じクラス、サブクラス、モジュール以外のメソッドを指定した場合に発生します。

irb(main):001* class Foo
irb(main):002*   def foo() p :foo end # レシーバのないメソッドを作成
irb(main):003*   define_method(:bar, instance_method(:foo)) # 作成されたメソッドがbarというメソッド名にもなる
irb(main):004> end
irb(main):005> Foo.new.bar
:foo
=> :foo
irb(main):029> Foo.new.foo
:foo
=> :foo

UnboundMethodクラスとは レシーバがないと動作しない

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?