In the previous blog, such code 1 class songlist was used.
2 def [] (key)
3 return @ songs [Key] If key. kind_of? (Integer)
4 return @ songs. Find {| Asong. Name = key}
5 end
6end
In the fourth row, a method such as find can traverse the songs according to the specified conditions, and finally return an individual that meets the conditions.
Next let's take a look at how this method is implemented. 1 class Array
2 def find
3 For I in 0 size
4 value = self [I]
5 return value if yield (value)
6 end
7 return Nil
8 end
9end
10
It is found that a method is added to the array class and a traversal operation is embedded in the method.
If this is the case, there will be no difference between Ruby and other languages. We have noticed that yield exists in line 5th.
Such a stuff. In fact, he acts as a proxy, realizing the separation of actual operation parts and traversal.
Let's take a look at the example below to understand the yield function.
1def threetimes
2 Yield
3 yield
4 yield
5end
6 threetimes {puts "hello "}
7
8
Here we define the blocks named threetimes. Blocks repeats three external operations. After Row 6 code is executed, the following result is displayed:
Hello
Hello
Hello
We can see that blocks provides us with such flexible means. In fact, blocks needs to be implemented through proxies, interfaces, or function pointers.
In fact, Versions later than. Net 3.x also provide similar functions, a plug-in called language integrated query.
You can use SQL-like methods to filter sets.
LINQ query:
String [] names = {"Geoff", "Jessica", "Mike", "Megan ",
"Priscilla", "Jack", "Alma "};
Ienumerable <string> expr = from S in names
Where S. Length = 5
Orderby s
Select S. toupper ();
Foreach (string item in expr)
Console. writeline (item );
Is the above usage simple and convenient?
If Ruby is used for implementation, it will be like this:
1 Names = ["Geoff", "Jessica", "Mike", "Megan", "Priscilla ",
2 "Jack", "Alma"]
3
4 expr = names. Select {
5 | n. Length = 5
6}. Sort. Collect {| n. upcase}
7
8expr. Each {| n | puts n}
Blocks is so convenient that it is widely used when reading Ruby programs.