Tbpgr Blog

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

Ruby | Method | to_proc

概要

Method#to_proc -> Proc

詳細

self を call する Proc オブジェクトを生成して返却。

サンプルコード

1.rb

require 'tbpgr_utils'

class Hoge
  def hoge1
    "hoge"
  end

  def hoge2(param1, param2)
    [param1, param2]*2
  end
end

h = Hoge.new
m1 = h.method(:hoge1)
m2 = h.method(:hoge2)


bulk_puts_eval binding, <<-EOS
m1.to_proc
m2.to_proc
m1.to_proc[]
m2.to_proc["hoge", "hige"]
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

2.rb

class Hoge2
  def hoge; end
end

出力

m1.to_proc                 # => #<Proc:0x2635f68 (lambda)>
m2.to_proc                 # => #<Proc:0x2635578 (lambda)>
m1.to_proc[]               # => "hoge"
m2.to_proc["hoge", "hige"] # => ["hoge", "hige", "hoge", "hige"]