The use of Block and iterator in Ruby is explained by rubyblock.

Source: Internet
Author: User

The use of Block and iterator in Ruby is explained by rubyblock.

Let's briefly describe a unique feature of Ruby. Block, a code Block that can be associated with a method call, almost like a parameter. This is an incredible feature.

You can use Block to implement callback (but it is simpler than the anonymous internal class of Java (anonymous inner) and pass a set of code (but it is far more flexible than the function pointer of c ), and implement the iterator.

Block is just a set of code between curly braces or do... end.

{puts "Hello"}             #this is a blockdo                      ###  club.enroll(person)            #and so is this person.socialize              #end                     ###

Why are there two delimiters? Some people think that sometimes it is more natural to use a separator than the other one. Another reason is that they have different priorities: curly braces are closer than do/end bindings. We try to follow the conventions that are becoming Ruby standards. single block uses curly brackets and multiple block uses do/end.

Once a block is created, it can be associated with a method call. Place the beginning of the block at the end of the source code line containing the method call to implement Association. For example, in the following code, the block containing puts "Hi" is associated with the call of the greet method.

greet {puts "Hi"}

If the methods have parameters, they appear before the block.

verbose_greet("Dave","loyal customer"){puts "Hi"}

Then, you can use the Ruby yield statement to call the associated block one or more times. You can think of yield as a method call. It calls the block associated with the method containing the yield statement.

The following example shows how to use the yield statement. Defines a method that calls yield twice. Call this method, place the block in the same row, after the method is called (and after all the parameters of the method ).

def call_block puts "Start of method" yield yield puts "End of method"endcall_block{puts "In the block"}

Output result:

 Strat of method In the block In the block End of method

Parameters can be provided to yield for calling. parameters are passed to the block. In a block, parameter names are provided between vertical bars (|) to accept these parameters from yield.

 def call_block  yield("Hello",99) end call_block {|str,num| ...}

A large number of blocks are used in the Ruby library to implement the iterator. The iterator is a method to continuously return elements from a collection, such as an array.

Animals = % w (ant bee cat dog elk) # create an array animals. each {| animal | puts animal} # iterate its content

Output result:

antbeecatdogelk

Let's take a look at how to implement the each iterator applied to the Array class in the previous example. The each iterator processes the elements in the array cyclically and calls yield for each element. In the pseudo code, it may be written:

# In the Array class... def each for each element # <-- invalid Ruby statement yield (element) endend

Many loop structures built in languages such as c and java are only method calls in Ruby. These methods call the associated block zero or multiple times.

['cat','dog','horse'].each{|name| print name," "}5.times {print "*"}3.upto(6){|i| print i}('a'..'e').each{|char| print char}

Output result:

cat dog horse *****3456abcde

The code above requires the object to call the block five times; then requires object 3 to call a block and pass in a continuous value until the value reaches 6. Finally, use the each method to call the block for the character range (range) between a and e.

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.