The emergence of the Ruby language has changed the traditional coding method of programmers, so that programmers can have a very pleasant mood when writing code. Here we will introduce you to Ruby blocks, a flexible encoding method.
- Ruby Rmagick Installation Guide
- Ruby special syntax concepts
- Example of Ruby code for getting the current class name
- Ruby module OpenURI to get http/FTP address content
- Analysis of Ruby encryption implementation code examples
Let's take a look at this Code:
- Class SongList
- Def [] (key)
- Return @ songs [key] if
Key. kind_of? (Integer)
- Return @ songs. find {
| ASong. name = key}
- End
- End
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.
- class Array
- def find
- for i in 0size
- value = self[i]
- return value if yield(value)
- end
- return nil
- end
- end
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 1, 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
- yield
- yield
- yield
- end
- threeTimes { puts "Hello" }
Here we define the blocks named threeTimes. The Ruby blocks will repeat three external operations. After row 6 code is executed, we will get the following results:
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 LINQLanguage Integrated Query.
You can use SQL-like methods to filter sets.
- LINQ Query:
- string[] names = { "Geoff",
"Jessica", "Mike", "Megan",
- "Priscilla", "Jack", "Alma" };
- IEnumerable 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:
- names = [ "Geoff", "Jessica",
"Mike", "Megan", "Priscilla",
- "Jack", "Alma" ]
- expr = names.select {
- |n| n.length == 5
- }.sort.collect { |n| n.upcase }
- expr.each {|n| puts n }
Ruby blocks is so convenient that it is widely used when reading ruby programs.