2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

lambdaとは

2
Posted at

lambdaとは

ラムダ(lambda)を一言で言うと、
「あとで実行できる、名前のない小さなメソッド」らしい。

無名関数(名前のないメソッド)を作るための仕組み。
Rubyには無名関数として lambda と Proc の2種類があり、見た目は似ているが振る舞いに重要な違いがある。
Procはこっちに詳しく書きました。

Rubyにおけるラムダの書き方

Rubyではラムダは主に2通りある。

① -> を使う書き方(現在主流・推奨)

add = ->(e) { e.upcase }
puts add.call("hello")
# HELLO

->(引数) { 処理 }
引数は 必ず () の中
ブロック引数の |e| は使えない

② lambda メソッドを使う書き方(昔からある)

add = lambda { |e| e.upcase }
puts add.call("hello")
# HELLO

こちらは ブロック構文
引数は | | を使う

lambda と Proc の違い

① 引数の扱い(ここが一番大事)

l = lambda { |a, b| a + b }
p = Proc.new { |a, b| a + b }

l.call(1)   # ❌ エラー(引数が足りない)
p.call(1)   # ✅ エラーにならない(bはnil)

・lambdaは厳密(メソッドと同じ)
・ Procはゆるい

② return の動き

def test_lambda
  l = lambda { return "lambda" }
  l.call
  return "method"
end

def test_proc
  p = Proc.new { return "proc" }
  p.call
  return "method"
end

puts test_lambda  # => "method"
puts test_proc    # => "proc"

・lambda の return
→ lambdaの処理だけ を終わらせて、呼び出し元に戻る

・Proc の return
→ Procを定義したメソッド自体 を 強制終了する

③ メソッドっぽさ

・lambda:メソッドに近い(安全・厳密)

・Proc:ブロックに近い(柔軟)

まとめ表

項目 lambda Proc
引数チェック 厳密 ゆるい
return 自分の中だけ メソッド全体
性格 メソッド寄り ブロック寄り
よく使う場面 安全に関数として使う 柔軟な処理

※基本は lambda を使う(バグが起きにくい)
Rubyの内部処理やDSLでは Proc が使われることもある

2
0
1

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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?