A brief description of the iterator _ruby topic in Ruby

Source: Internet
Author: User
Tags arrays hash

Iterators are methods that are supported by collections. An object that stores a set of data members is called a collection. In Ruby, arrays and hashes can be called collections.

The iterator returns all the elements of the collection, one after the other. Here we'll discuss two kinds of iterators, each and collect.
Ruby each iterator

Each iterator returns all elements of an array or hash.
Grammar

Collection.each do |variable|
  Code End


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

#!/usr/bin/ruby

ary = [1,2,3,4,5]
Ary.each do |i|
  Puts I end


This will produce the following results:

1
2
3
4
5

Each iterator is always associated with a block. It returns each value of the array to the block, one after the other. The value is stored in the variable i and then displayed on the screen.
Ruby Collect iterator

The Collect iterator returns all the elements of the collection.
Grammar

Collection = Collection.collect

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

#!/usr/bin/ruby

a = [1,2,3,4,5]
B = array.new
B = A.collect
puts b

This will produce the following results:

1
2
3
4
5

Note: The Collect method is not the correct way to replicate between arrays. Here is another method called Clone, which is used to copy an array to another array.

When you want to do something with each value to get a new array, you typically use the Collect method. For example, the following code generates an array with a value of 10 times times each value in a.

#!/usr/bin/ruby

a = [1,2,3,4,5]
b = a.collect{|x| 10*x}
puts b

This will produce the following results:

50

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.