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.
- def traverse(visit_proc, proc)
- i = 0
- while (i < 10)
- visit_proc.call(i, i + 1)
- proc.call
- i += 1
- end
- end
- def visit_node(i, j)
- print("#{i}, #{j}")
- puts
- end
- def print_sharp
- puts("###################")
- end
- 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.