Proc & Lambda & Block

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 between do and end.
  • 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.