Ruby function pointer concepts

Source: Internet
Author: User

There are also pointers in the Ruby language that are recognized by programmers as the most difficult to understand. But what are the new features of pointers in this new language. Next, let's take a look at some concepts related to Ruby function pointers.

  • Special Ruby Variables
  • Ruby naming rules
  • Basic Syntax of common Ruby Libraries
  • Using pp () to output two-dimensional arrays in Ruby
  • Ruby on Rails directory files

I am studying the Ruby language again, so that I can reach a certain level of proficiency. Seeing the block part reminds me of the very friendly function pointers in C, C ++, and C. This feature is useful in implementing the visitor mode. The last section in the HTML Version of Programming Ruby introduces the visitor mode implementation method. I have not seen it yet. Here is my method.

Ruby's block function can only plug in a piece of code. Compared with the Ruby function pointers in the C language family. The Proc class of the core library can encapsulate block code. With this function, you can pass multiple blocks together as parameters to the call function. The following code demonstrates a specific process. The visit_node method, together with the proc method, acts as a function with two parameters and is passed to the traverse call. Note that the last line encapsulates the visit_node and proc methods into Proc objects.

 
 
  1. def traverse(visit_proc, proc)  
  2. i = 0 
  3. while (i < 10)  
  4. visit_proc.call(i, i + 1)  
  5. proc.call  
  6. i += 1  
  7. end  
  8. end  
  9. def visit_node(i, j)  
  10. print("#{i}, #{j}")  
  11. puts  
  12. end  
  13. def print_sharp  
  14. puts("###################")  
  15. end  
  16. traverse(Proc.new { |i, j| 
    visit_node(i, j) }, Proc.new 
    { print_sharp }) 

In this way, we can achieve the effect similar to the Ruby function pointer. It is somewhat similar to the proxy in C.

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.