A lambda is simply an anonymous function. Ruby has lambdas as well, but they’re
commonly called proc objects.
sum = proc {|a,b| a + b}
sum.call(3, 4) # => 7
You could also write this:
sum = lambda {|a,b| a + b}
sum.call(3, 4) # => 7
A block allows you to inject code into a function/method at a certain point.
def countUp(n)
1.upto(n) do |num|
yield num
end
end
countUp(5) {|myNum| puts n * n}
1
4
9
16
25
It may help to think of a block as a user-definable co-routine. You can also
convert a block into a proc object by prefixing the last argument of a method
with an ampersand.
def doSomething(&p)
p.call
end
doSomething { puts “Hello” }
Hello
This can be helpful in a number of ways, and it’s pretty much required to
inject code into a recursive function (i.e.,)
def dir_recurse(dirname, &action)
Dir.open(dirname) do |dir|
dir.each do |file|
if test(?d, “#{dirname}/#{file}”) and not test(?l, “#{dirname}/#{file}”)
next if file =~ /^..?$/
dir_recurse("#{dirname}/#{file}", &action)
else
action.call("#{dirname}/#{file}")
end
end
end
end
display each file in /sbin
dir_recurse("/sbin") {|file| puts file}
show mtime of all files in /tmp
dir_recurse("/tmp") {|file| puts “#{file} #{File.mtime(file)}”}
Hope this helps,
Travis