Tbpgr Blog

元エンジニア 人事 tbpgr(てぃーびー) のブログ

Ruby | Proc/lambdaとcallとcase

概要

Proc/lambdaとcallとcase

詳細

Proc/lambdaは通常呼び出し方には様々な形式があります。

self[*arg] -> ()[permalink][rdoc]
call(*arg) -> ()
self === *arg -> ()
yield(*arg) -> ()

「===」はcase whenを利用する際を想定して用意されています。

Proc/lambdaの様々な呼び出し方

サンプルコード
require 'tbpgr_utils'

increment1 = lambda{|a|a + 1}
increment2 = -> (a) {a + 1}
[*1..3].each do |v|
  bulk_puts_eval binding, <<-EOS
v
increment1.call v
increment2.call v
increment1 === v
increment2 === v
increment1.(v)
increment1.(v)
increment2.(v)
increment1[v]
increment2[v]
increment1.yield v
increment2.yield v
  EOS
end

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
v # => 1
increment1.call v # => 2
increment2.call v # => 2
increment1 === v # => 2
increment2 === v # => 2
increment1.(v) # => 2
increment2.(v) # => 2
increment1[v] # => 2
increment2[v] # => 2
increment1.yield v # => 2
increment2.yield v # => 2
v # => 2
increment1.call v # => 3
increment2.call v # => 3
increment1 === v # => 3
increment2 === v # => 3
increment1.(v) # => 3
increment2.(v) # => 3
increment1[v] # => 3
increment2[v] # => 3
increment1.yield v # => 3
increment2.yield v # => 3
v # => 3
increment1.call v # => 4
increment2.call v # => 4
increment1 === v # => 4
increment2 === v # => 4
increment1.(v) # => 4
increment2.(v) # => 4
increment1[v] # => 4
increment2[v] # => 4
increment1.yield v # => 4
increment2.yield v # => 4

case when と lambda

サンプルコード
require 'tbpgr_utils'

ret = [*1..30].reduce([]) do |r, v|
  case v
  when -> (x) {x % 15 == 0}
    r << "fizzbuzz"
  when -> (x) {x % 3 == 0}
    r << "fizz"
  when -> (x) {x % 3 == 0}
    r << "fizz"
  else
    r << v
  end
  r
end.join(",")

print ret

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils
出力
1,2,fizz,4,5,fizz,7,8,fizz,10,11,fizz,13,14,fizzbuzz,16,17,fizz,19,20,fizz,22,23,fizz,25,26,fizz,28,29,fizzbuzz