Skip to content

Instantly share code, notes, and snippets.

@takumikinjo
Created February 29, 2012 15:15
Show Gist options
  • Save takumikinjo/1941474 to your computer and use it in GitHub Desktop.
Save takumikinjo/1941474 to your computer and use it in GitHub Desktop.
lambda-and-proc
# -*- coding: utf-8 -*-
# lambda で Proc オブジェクトを作る
def foo(v)
f = lambda { |a, b|
puts "#{a}, #{b}, #{v}"
}
end
# Proc.new で Proc オブジェクトを作る
def bar(v)
f = Proc.new { |a, b|
puts "#{a}, #{b}, #{v}"
}
end
# lambda 中で return する
def foo2(v)
f = lambda { |a, b|
return true
puts "#{a}, #{b}, #{v}"
}
end
# Proc.new の中で return する
def bar2(v)
f = Proc.new { |a, b|
return true
puts "#{a}, #{b}, #{v}"
}
end
# &proc を呼ぶ
def baz(&proc)
proc.call(2)
end
# yield で呼ぶ
def baz2
yield(2)
end
puts "lambda で作った Proc オブジェクトを呼んでみる"
f = foo(999)
f.call(1, 2)
puts "引数を少なく呼べるか? => 例外になる"
begin
f.call(1)
rescue => e
puts e
end
puts "Proc.new で作った Proc オブジェクトを呼んでみる"
g = bar(999)
g.call(1, 2)
puts "引数を少なく呼べるか => 呼べる"
g.call(1)
puts "lambda で作った Proc オブジェクトから return できるか? => できる"
f = foo2(999)
if f.call(1, 2) == true
puts "returned"
end
puts "Proc.new で作った Proc オブジェクトから return できるか? => 例外になる"
g = bar2(999)
begin
g.call(1, 2)
rescue => e
puts e
end
puts "引数 1 つで &proc 呼ぶ => 呼べる => &proc は Proc.new のものと同質"
baz { |a, b|
puts "#{a},#{b}"
}
puts "引数 1 つで yield を呼ぶ => 呼べる => yield は Proc.new のものと同質"
baz2 { |a, b|
puts "#{a},#{b}"
}
puts "&proc の中から return できる? => 例外"
begin
baz { |a| return true }
rescue => e
puts e
end
puts "yield の中から return できる? => 例外"
begin
baz2 { |a| return true }
rescue => e
puts e
end
puts "each の中から return できる? => 例外"
begin
[0, 1].each { |a| return true }
rescue => e
puts e
end
# -*- coding: utf-8 -*-
def open_database
puts "open database"
end
def close_database
puts "close database"
end
def write_data_easy(&block)
open_database
block.call
close_database
end
puts "=== 普通のデータ書き込みはこう書くとする"
open_database
puts "wrote data"
close_database
puts "=== &block を使うとこう書ける"
write_data_easy do
puts "wrote data"
end
# rails などのフレームワークを使ってプログラムする場合
# &block を使う場面は少ない
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment