Blocks, procs and lambdas Flashcards
What is a ruby block?
A block is a bit of code that can be executed
You can use do …end or { } brackets
What is the collect method?
The collect method takes a block and applies the expression in the block to every element in an array
my_nums = [1, 2, 3] my_nums.collect { |num| num ** 2 } # ==> [1, 4, 9]
What is the yield keyword?
The yield keyword, when used inside the body of a method will allow you to call that method with a block of code and pass the torch or yield to that block.
Think of the yield keyword as stop executing the code in this method, go and instead execute the code in this block. Then return to the code in the method.
Are blocks objects?
No blocks are not objects and can therefore not be saved to a variable.
What are Procs?
Procs are saved blocks that you can name and turn into a method.
What are Procs used for?
Procs are used for keeping the code dry.
What is Dry
A programming concept : Don’t Repeat Yourself.
How do you create a Proc?
with Proc.new
cube = Proc.new { |x| x ** 3 }
What are the advantages of Procs?
1) They are objects
2) They can be reused.
How can you call on a Proc?
By using the .call method
How do you convert a symbol into a Proc?
with the & symbol.
How do you write a lambda?
lambda { | param | block }
What is the difference between lambdas and procs?
Lambda checks the number of arguments.
Lambdas count the arguments.
A lambda passes control back to the calling method.
Procs do not count the argument passed to them it just ignores needless arguments.
When are Curly braces required in ruby?
When you want to put the code in one single line.
Why would you like to use a Proc instead of a regular Method?
- Gives more flexibility
- you can store more in a variable
- required in the database syntax