Brief description of the iterator in Ruby and brief description of the Ruby Generator

Source: Internet
Author: User

Brief description of the iterator in Ruby and brief description of the Ruby Generator

The iterator is a method supported by the set. Objects that store a group of data members are called collections. In Ruby, arrays and hashes can be called collections.

The iterator returns all elements of the set, one after another. Here we will discuss two types of iterators, each and collect.
Ruby each iterator

The each iterator returns all elements of an array or hash.
Syntax

collection.each do |variable|  codeend

Executes code for each element in the set. Here, the set can be an array or a hash.
Instance

#!/usr/bin/rubyary = [1,2,3,4,5]ary.each do |i|  puts iend

This produces the following results:

12345

The each iterator is always associated with a block. It returns each value of the array to the block, one after another. The value is stored in variable I and displayed on the screen.
Ruby collect iterator

The collect iterator returns all elements of the set.
Syntax

collection = collection.collect

The collect method does not always need to be associated with a block. The collect method returns the entire set, whether it is an array or a hash.
Instance

#!/usr/bin/rubya = [1,2,3,4,5]b = Array.newb = a.collectputs b

This produces the following results:

12345

Note: The collect method is not the correct method for copying between arrays. Here is another method called clone, used to copy an array to another array.

When you want to perform operations on each value to obtain a new array, you usually use the collect method. For example, the following code generates an array whose value is 10 times that of each value in.

#!/usr/bin/rubya = [1,2,3,4,5]b = a.collect{|x| 10*x}puts b

This produces the following results:

1020304050

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.