Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any "simple" explanations of what procs and lambdas are in Ruby?

Tags:

Are there any "simple" explanations of what procs and lambdas are in Ruby?

like image 325
yazz.com Avatar asked Nov 16 '09 08:11

yazz.com


1 Answers

Lambdas (which exist in other languages as well) are like ad hoc functions, created only for a simple use rather than to perform some complex actions.

When you use a method like Array#collect that takes a block in {}, you're essentially creating a lambda/proc/block for only the use of that method.

a = [1, 2, 3, 4]
# Using a proc that returns its argument squared
# Array#collect runs the block for each item in the array.
a.collect {|n| n**2 } # => [1, 4, 9, 16]
sq = lambda {|n| n**2 } # Storing the lambda to use it later...
sq.call 4 # => 16

See Anonymous functions on Wikipedia, and some other SO questions for the nuances of lambda vs. Proc.

like image 147
jtbandes Avatar answered Oct 11 '22 12:10

jtbandes