In Ruby, Block, Proc and Lambda are all ways to create anonymous functions or code blocks that can be passed around and executed later.
Block: ๐งฑ๐ง
Definition:
- A block is a chunk of code enclosed within
{}
or betweendo
andend
. - A block is like a ninja ๐ฅท hiding inside your code, waiting to execute a special mission whenever a method calls for its assistance! ๐
Use Case:
- ‘Blocks‘ are commonly used with methods that accept them. They allow you to pass a piece of code to a method for execution.
Proc: ๐ฑ๐จโ๐ณ
Definition:
- A Proc is a saved block of code that can be stored in a variable and reused.
- A Proc is like a little bundle of code that you can carry around and use whenever you want.
- A Proc is your code’s personal chef ๐ณ – you tell it what ingredients (arguments) to cook with, and it whips up a delicious dish (code) that you can savor anytime! ๐
Use Case:
- Procs are handy when you want to store a piece of code for later execution, perhaps to be used in different parts of your program.
Lambda: ๐ฆโจ
Definition:
- A lambda is a type of Proc with stricter argument checking and a more method-like behavior.
- A lambda is the superhero ๐ฆธโโ๏ธ version of a Proc, with a strict cape enforcing rules. It’s like Batman, but for your code, making sure everything follows a specific plan! ๐ฆ๐ป
Use Case:
- Lambdas are suitable when you need a block of code that behaves like a function and enforces the number of arguments.