Ruby Way's advanced OOP features II

Source: Internet
Author: User

1 storing the code like an object

When you want to store a piece of code in the form of an object, Ruby gives you several methods. Here we'll introduce the Proc object, the method object, and the Unboundmethod object.

The built-in proc class wraps Ruby block to an object. A Proc object, like a blocks, is a closure and preserves the context in which it is defined:

Ruby Code

MyProc = proc.new {|a| puts "Param is #{a}"}
Myproc.call (?) # Param is 99 

The Proc object is created automatically when a method accepts a & parameter, and then the method is invoked immediately after a block is called:

Ruby Code

def take_block (x, &block)
puts Block.class
x.times {|i| block[i, I*i]}
end
take_block (3) { |n,s| Puts "#{n} squared is #{s}"} 

Note here that the [] method is an alias to the call method.

If you have a Proc object, you can pass it to a method that can receive blocks. Just add & in front of it.

Ruby Code

MyProc = proc {|n| print n, "... "}
(1..3). each (&myproc) # 1 ... 2.. 3...

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.