Use of each and collect in Ruby for iteration, rubycollect

Source: Internet
Author: User

Use of each and collect in Ruby for iteration, rubycollect

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

The iterator returns all elements of a set, one before and one after. We will discuss two iterators, each of which is collected here. Let's take a look at these details.
Ruby each iteration:

Each iterator returns all elements or hash of an array.
Syntax:

collection.each do |variable|  codeend

Code executed by each element in the set. The collection may be an array or ruby hash.
Example:

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

The result is as follows:

12345

You are always associated with each iteration of the block. It returns each value of the array, one by one. The value is stored in variable I and displayed on the screen.
Ruby collect iteration:

The collected iterator returns all elements of a set.
Syntax:

collection = collection.collect

The collection method does not always require blocks. The collection method returns the entire set, whether it is an array or a hash.
For example:

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

This produces the following results:

12345

Note: The collection method is incorrect for copying between arrays. Another method is clone. Copy one array to another.

You usually use the collection method when you want to do something with each value to get a new array. For example, this code contains 10 times of each value and generates an array B.

#!/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.