Block/Proc/Lambda
Recycle, Reduce and Re-use Code
11.01.2015
Blocks, Procs, and Lambdas are a type of code that act upon an object in Ruby.
Blocks are very general. You can call a block of code on an object. Blocks are usually recongnizable by their do...end syntax or {...} . That means that anything within that structure will be ran to the object it is called upon.
For example, let's take an array of numbers, [3,10,5,6,8] and call the each method to it so it will run our block of code on each element of the array.
[3,10,5,6,8].each do
#code goes here
end
So now, we have created the skeleton for whatever code we want to run on each number in the array. The block part is whatever we put inside the do and end. Let's square each number!
[3,10,5,6,8].each do |x|
puts x*2
end
The result for this will be:
9
100
25
36
64
The block literally took the square of each number and put it on a line.
Procs is short for procedure! With Proc you can set a block of code to a variable and reuse that block of code whenever you want. Proc is a class, so to create a new instance of Proc, you call it with typical class notation
variable_name = Proc.new{#code goes here}
Now, we can put whatever block of code we want to repeat inside the brackets and then apply that code to objects. Let's make a block of code that prints everything out with a smiley face at the end.
smiles = Proc.new {|x| puts "-" + x + ":)" }
We've names the block of code smiles. Now we can simply use that name in place of the block of code. There are a few different ways to use Proc and call the new procedures, but for this case, we will call it an an array. NOTE: place a & before the Proc name to call the block.
words = ["I'm","walking","on","sunshine"]
words.each(&smiles)
-I'm :)
-walking :)
-on :)
-sunshine :)
Now we've packaged that block and can use it over and over by using &smiley!
Finally, Lambda is a very specific type of Proc. They basically do the same thing, but lambdas are picky about the # of arguements passed to it and lambda gives more control the calling method than proc. You don't need .new to create a lambda. Let's create a lambda that converts numbers to strings.
numbers = [1,4,5,7,9]
conversion = lambda { |x| x.to_s}
numbers.collect!(&conversion)
>>["1", "4", "5", "7", "9"]
This returned a new array with the numbers as strings. Notice we use the same & symbol to call lambdas as we do to call procs.
Return to list of blog posts.