How to implement Ruby function callback

Source: Internet
Author: User

It's been confusing. Ruby is not like python,c can pass functions at will, and then execute them when needed. The essential reason is that Ruby's function is not an object.

The following methods can be used to find out the data:

def func (A, b)   += method (: Func) F.call (1, 2)

It uses the method object to encapsulate the function, and then you can pass the parameter of the function by manipulating the method object.

Once thought that the above method is the function as a parameter to use the Orthodox method, later found that I was too attached to the C function pointer usage pattern, and did not really understand the essence of the Ruby block, using block implementation method:

def func (A, b)   + Benddef  Use_func (A, b)  yield  A, Benduse_func (1, 2) do |a, b|< c14>  func A, bend

Explain the intent:

Passing a function as a parameter to another object is essentially intended to allow other objects to use the function, as is the case with the Use_func implementation, when the concern is simply the parameter list and the return value, that is, we can use block to pass the "shape" of the Func to Use_func , and then execute func in the block when you really need to use Func.

Of course, the example of the Func implementation is too simple, you may think that only need to put the puts statement in block, but when the implementation of the content increased or need to reuse, the Func is still necessary.

How to implement Ruby function callback

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.