proc和lambda最主要的区别就是可以把lambda看作和定义一个方法的行为是一致的,而proc是一个真正意义上的代码块。
## case 1
a = proc { |x| x }
p a.call # => nil
b = lambda { |x| x }
p b.call(2) # => exception if none
## case 2
def hi
a = proc { return 3 }
a.call
4
end
def hello
a = lambda { return 5 }
a.call
6
end
p hi => 3
p hello => 6
## case 3
def hi x
x
end
p method(:hi).call(7) # to lambda
puts "*" * 50
## case last
def bar_1 &block
block.call
end
def bar_2
yield
end
require 'benchmark'
puts 'bar_1:'
p Benchmark.realtime {
1_000_000.times do
bar_1 { 'ok' }
end
}
puts 'bar_2:'
p Benchmark.realtime {
1_000_000.times do
bar_2 { 'ok' }
end
}