Ruby Study Notes (7)-closures

Source: Internet
Author: User

An important feature of closures is that variables defined inside a process (method) can be referenced even after the method call is complete! (That is, the lifecycle is extended)

Def method (n) puts "n = # {n}"; # Return proc {| I | n + = I} # key: Proc is a process object, it can only be called by "delegate". Here, the Parameter Variable N is referenced in the process. After multiple calls, N references are retained to form a closure! Endadelegate = method (0); # it can be understood as a delegate in C #. At the same time, this statement initializes n to 0 puts adelegate. call (1); # n = 0 after the last line is run, and then input parameter 1, equivalent to N = n + 1, that is, the final n = 1 puts adelegate. call (5); # Similarly, n = 6 puts adelegate. call (10); # N = 16
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.