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

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 224
    Comment on it

    About lambda:

    • Lambda are just like objects.
    • It is just like a regular function whose last statement is it's  returns value.
    • Syntax for lambda :  lambda = lambda {}

    Example1:

    l = lambda{"hello"}
    
    puts l.call

    Output: hello

     

    Example2:

    a = lambda do |s|
    
          if s == "hello"
    
            return "hello from ruby"
    
          else
    
            return "bye from ruby"
    
          end
    
         end
    
    puts a.call("hello")

    Output:  hello from ruby

     

    • Lambda is an instance of the Proc class.
    • We can use the return statement inside lambda which makes it more flexible.
    • Lambda will return values from lambda itself and not from block or proc.
    • Lambda does not have any names as though they behave like methods and they are very rarely in use.

    About Procs:

    • Procs are same as blocks but the only difference between procs and blocks is that we can store proc in a variable which makes it useful for future purpose.
    • We can also pass procs as arguments to functions.

    Example1:

    x = Proc.new do
    
          puts "hello everyone"
    
        end
    
    x.call

    Output: hello everyone

     

     

    About Blocks:

    • Unlike proc , block can't be stored in a variable.
    • Block is not considered as an object.
    • Unlike lambda in which we do not have to provide a name to it , in block we provide it with a name.
    • If we want to invoke a block , we call it by the same name as that of the block.
    • A block is always invoked with the help of the yield statement.

    Example1:

    block_name{
    
      statement1
    
      statement2
    
      ..........
    
      ..........
    
    }

    Example2:

    def example
    
      puts "This is the first example"
    
      yield
    
      puts "You are in the example"
    
      yield
    
    end
    
    example {"You are in the block example"}

    Output:

    This is the first example

    You are in the block example

    You are in the example

    You are in the block example

 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: