The similarities and differences between Ruby Proc and Lambda

Source: Internet
Author: User

What Proc and Lambda have in common:

    • Similar syntax
      proc.new{|n| N**2}

      lambda{|n| N**2}

    • Can be called with the. Call method

      Hello_proc = proc.new{puts "hello!"}
      Hello_proc.call #Hello!
      Hello_lambda = lambda{puts "hello!"}
      Hello_lambda.call #Hello!

    • can be converted to block with & keyword
      Nums = [1,3,4,5,6]
      Cube_proc = proc.new{|n| n**3}
      Cube_nums_proc = Nums.map (&cube_proc) #[1,27,64 ...]

      Cube_lambda = lambda{|n| n**3}
      Cube_nums_lambda = Nums.map (&CUBE_LAMBDA) #[1,27,64 ...]

    • Both are object

The difference between Proc and lambda:

    1. Lambda checks the parameters passed in, and if an incorrect argument is passed, throw an error; Proc does not check, even if an incorrect parameter is passed, it is ignored, and nil is assigned to the result (assign to any of that is nil missing.).
    2. When the lambda returns, the control is returned to its calling function, and proc is not exchanged.

      def Batman_ironman_proc
      Victor = proc.new {return "Batman'll win!"}
      Victor.call
      "Iron man would win!"
      End

      Puts Batman_ironman_proc

      def BATMAN_IRONMAN_LAMBDA
      Victor = lambda {return "Batman'll win!"}
      Victor.call
      "Iron man would win!"
      End

      Puts Batman_ironman_lambda

      Output = = = = = "Batman'll win!
      Iron man would win!

The similarities and differences between Ruby Proc and Lambda

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.