$30 off During Our Annual Pro Sale. View Details »

wnbrbmeetup_procslambdas_bhumi.pdf

Bhumi
September 28, 2022

 wnbrbmeetup_procslambdas_bhumi.pdf

Bhumi

September 28, 2022
Tweet

Other Decks in Programming

Transcript

  1. RUBY BLOCKS, PROCS, LAMBDAS Bhumi Shah @bhumi1102

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

    by a block ➤ seq(5, 2) { |x| puts x }
  3. 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 }
  4. 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
  5. HOW TO CREATE PROC AND LAMBDA

  6. INVOKING PROCS AND LAMBDAS

  7. 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
  8. RETURN STATEMENT - PROC

  9. RETURN STATEMENT - LAMBDA

  10. NUMBER OF ARGUMENTS

  11. HOW &: WORKS ➤ 1. Putting & in front of

    an object ➤ 2. Symbol classes to_proc method ➤ 3. Method names as symbols
  12. & 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.
  13. 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 }
  14. 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 }
  15. THE END ➤ Ruby Proc Docs https://ruby-doc.org/core-2.6/Proc.html ➤ Search your

    codebase for “Proc.new” or “lambda”