Ruby series: Block, Proc, Lambda)

Source: Internet
Author: User

Block, lambda, and proc are important in ruby.

    • A block is an anonymous function. It is called using a field in the called method. Block is mainly used for iteration.
RubyCode:

 

Arr = [1, 2, 4, 5]
Arr. Each {| item | puts item}

Proc is also a code block, which is equivalent to a process.
Ruby code:
A_proc = Proc. New {| A, * B | B. Collect {| I * }}
A_proc.call (9, 1, 2, 3) # => [9, 18, 27]
When Proc. New creates a proc object, it does not contain a block, but it only includes a block on the method for defining Proc. This block will become Proc.

Ruby code:

Def proc_from
Proc. New
End

 

Proc = proc_from {"hello "}
Proc. Call # => "hello"

The proc object is a code block bound to a local variable. After binding, the code can be called in different contexts and can access local variables.

 

Ruby code
Def gen_times (factor)
Return Proc. New {| n | N * factor}
End

 

Times3 = gen_times (3)
Times5 = gen_times (5)

Times3.call (12) # => 36
Times5.call (5) # => 25
Times3.call (times5.call (4) # => 60

Lambda is also an anonymous function.

 

Ruby code
A_lambda = Lambda {| A | puts}
A_lambda.call ("samsam ")

 

Lambda returns a proc object.

Ruby code

A_lambda.class # => proc

Lambda and proc are the same, except that the return of Proc will jump out of the called method, Lambda will not, It just returns itself.

Ruby code

 

Def foo
F = Proc. New {return "return From Foo from inside proc "}
F. Call # control leaves foo here
Return "return from foo"
End

Def bar
F = Lambda {return "return from lambda "}
Puts F. Call # control does not leave bar here prints "return from lambda"
Return "return from Bar"
End

Puts Foo # prints "return From Foo from inside proc"
Puts bar # prints "return from Bar"

 

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.