Upgrade to Pro — share decks privately, control downloads, hide ads and more …

wnbrbmeetup_procslambdas_bhumi.pdf

Bhumi
September 28, 2022

 wnbrbmeetup_procslambdas_bhumi.pdf

Bhumi

September 28, 2022
Tweet

Other Decks in Programming

Transcript

  1. BLOCKS AND YIELD ➤ All method innovations can be followed

    by a block ➤ seq(5, 2) { |x| puts x }
  2. NAMED BLOCK ➤ We can pass in a named block

    to a method ➤ We call it the same way still seq(5, 2) { |x| puts x }
  3. BLOCKS ARE NOT OBJECTS ➤ Blocks are syntactic structure in

    Ruby. They are not objects. ➤ But it is possible to create an object that represent a block. Depending on how we do that they are called a proc or a lambda ➤ Both procs and lambdas are instance of the same class called Proc ➤ Procs have block-like behavior and lambdas have method like behavior
  4. HOW PROCS AND LAMBDAS DIFFER ➤ A proc is an

    object form of a block ➤ A lambda is an object form of a method ➤ Calling a proc is like yielding to a block ➤ Calling a lambda is like invoking a method. ➤ This effects return statement and argument passing
  5. HOW &: WORKS ➤ 1. Putting & in front of

    an object ➤ 2. Symbol classes to_proc method ➤ 3. Method names as symbols
  6. & IN FRONT OF A PROC OBJECT ➤ When &

    is used before a Proc object in a method invocation, it treats the Proc as if it was an ordinary block following the invocation.
  7. METHOD AS SYMBOLS ➤ All method names are available by

    their symbol names ➤ 1.to_s is the same as 1.send(:to_s) ➤ :foo.to_proc is same as lambda {|x| x.foo }
  8. HOW USERS.MAP(&:FIRST_NAME) WORKS ➤ Symbol’s to_proc method is used to

    convert :first_name to a Proc object ➤ & is used to cast the Proc object to the block it represents. ➤ And that’s how users.map(&:first_name) becomes a widely used shorthand users.map { |u| u.first_name }