Having a problem understanding the difference between ruby blocks, procs and lamdas. What are the blocks? What is the difference between procs and lambdas? Let's break this down.
BLOCKS:
A block is a collection of code enclosed in a do/end statement or between braces { }. They are chunks of code that you can pick up and drop into another method as input or chunk of code that you associate with a method call. If you have used each before to loop through an Enumerable then you have used blocks.
Defining a block
def block_method
puts "we are in the method"
end
block_method { puts "The block is called"}
PROCS
So what if you want to pass two blocks to your function. How can you save your block into a variable?
Ruby introduces procs so that we are able to pass blocks around. Proc objects are blocks of code that have been bound to a set of local variables.Once bound, the code may be called in different contexts and still access those variables.
Defining procs
You can call new on the Proc class to create a proc . You can use the kernel object proc. Proc method is simply an alias for Proc.new. This can be assigned into a variable.
factor = Proc.new {|n| print n*2 }
or
factor = proc {|n| print n*2}
//using the proc value
[3,2,1].each(&factor)
>642
LAMBDAS
Can be defined using the method lambda or can be defined as stuby lambda
lamb = lambda {|n| puts 'I am a lambda' }
lamb = -> (n) { puts 'I am a stuby lambda' }
Difference between Procs and Lambdas
Procs donโt care about the correct number of arguments, while lambdas will raise an exception.
Return and break behaves differently in procs and lambdas
Next behaves same way in both procs and lambdas
References
rubyguides.com : Click Here!!!!
I hope that helps someone. Thanks :).
Thanks for reading. ๐
Iโd love to hear thoughts or comments around this. Feel free to email me at ronakabhattrz@gmail.com or hit me up on twitter, @ronakabhattrz .
Top comments (0)