Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | Method | unbind

概要

Method#unbind -> UnboundMethod

詳細

self のレシーバとの関連を取り除いた UnboundMethod オブジェクトを生成して返却。

サンプルコード
require 'tbpgr_utils'

class Hoge
  def hoge
    "hoge"
  end
end

h1 = Hoge.new
m1 = h1.method(:hoge)

bulk_puts_eval binding, <<-EOS
m1.unbind
m1.unbind.bind(Hoge.new)
m1.unbind.bind(Hoge.new).call
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

m1.unbind                     # =>       #<UnboundMethod: Hoge#hoge>
m1.unbind.bind(Hoge.new)      # =>       #<Method: Hoge       #hoge>
m1.unbind.bind(Hoge.new).call # => "hoge"