LoginSignup
1
1

More than 5 years have passed since last update.

Ruby|UnboundMethodで遊んでみた

Posted at

UnboundMethodは仕事では直接的にはお世話になりませんが、
何事もやってみることもありだと思うのでちょっと遊んでみました。

マニュアルによると、instance_methodを使うと良さそうです。

class Hoge
  def initialize(val)
    @val = val
  end

  def val
    @val
  end

  class << self
    def class_method
      15
    end
  end
end

unbind_method = Hoge.instance_method(:val)
hoge = Hoge.new(20)

p unbind_method.bind(hoge).call  #=> 20

Moduleクラスに定義されているので、必然的にクラスがレシーバーになります。
インスタンスメソッドだけはつまらないので、クラスメソッドにも同じことをやってみます。

特異クラスを取得して、class_methodメソッドを引数に渡して実現しています。

singleton = Hoge.singleton_class
unbind_class_method = singleton.instance_method(:class_method)

p unbind_class_method.bind(Hoge).call #=> 15

Methodオブジェクトを作ってからあえてunbindメソッドを呼び出して実現しています。
こっちのほうがシンプル?かなと

bind_class_method = Hoge.method(:class_method)
unbind_class_method = bind_class_method.unbind

p unbind_class_method.bind(Hoge).call #=> 15
1
1
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
1
1