Tbpgr Blog

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

Ruby | Kernel | lambda

概要

Kernel#proc { ... } -> Proc
Kernel#lambda { ... } -> Proc

詳細

与えられたブロックから手続きオブジェクト (Proc のインスタンス) を返却。
Proc.new に近い。

処理の中断

nextで処理を中断します。

サンプルコード
require 'pp'

# 中断
lm1 =-> (x) {
  next '7!' if x == 7
  [*1..x]
}

print lm1.call(6), "\n"
print lm1.call(7), "\n"

begin
  lm1.call
rescue => e
  print e
end

# lambdaはreturnするとブロックを抜けるだけ
def use_lambda
  -> {return "inner"}.call
  "outer"
end

puts
print use_lambda, "\n"

# Proc.newはreturnするとメソッドを抜ける
def use_proc_new
  Proc.new {return "inner"}.call
  "outer"
end

print use_proc_new, "\n"