Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Use of lambda, Proc and Block in Ruby

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 206
    Comment on it

    Today we are going to see the basic differences between Block, Procs and Lambda. 

    All these three are commonly used as inputs to some iterators like each and map.

     

    • Blocks

    Blocks can't be stored in a variable and are not considered as an object.

    Blocks are simply few lines of codes that are used together as an input to another method.

    A block is always invoked with the help of the yield statement as follows 

        > ["one","two","three"].each { |letter| print "#{letter.upcase} " }
        ONE TWO THREE  => ["one", "one", "three"]
        > ["one","two","three"].each do |letter|
        >    print "#{letter.upcase}"
        > end
        ONE TWO THREE  => ["one", "one", "three"]

     

    • Procs

    Procs and blocks almost same but the only difference between procs and blocks is that we can store proc in a variable which makes it useful for the future purpose.

    We can also pass procs as arguments to functions.

    And Procs can be used separately several times.

    p = Proc.new { puts "Hello Tom" }
    p.call  # prints 'Hello Tom'
    p.class # returns 'Proc'
    a = p   # a now equals p, a Proc instance
    p       # returns a proc object '#<Proc:0x007f96b1a60eb0@(irb):46>'

     

    •  Lambda

    We can explicitly use return statement inside lambda because in this lambda it will only return from itself.

    The number of arguments which have to be passed to lambda is counted so we can't pass the wrong number of arguments.

    It is just like a regular function whose last statement is it's returned value as follows

    lam = lambda { |x| puts x }    # creates a lambda that takes 1 argument
    lam.call(2)                    # prints out 2
    lam.call                       # ArgumentError: wrong number of arguments (0 for 1)
    lam.call(1,2,3)                # ArgumentError: wrong number of arguments (3 for 1)

     

    or one more example

    def lambda_test
      lam = lambda { return }
      lam.call
      puts "Hello Tom"
    end
    
    lambda_test                 # calling lambda_test prints 'Hello Tom'

    So hope this blog was helpful to understand blocks, procs and lambdas.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: