Use each and collect for iterative usage in Ruby _ruby topics

Source: Internet
Author: User

An iterator is nothing but a collection of methods supported. 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 a collection, one after the other. We'll talk about two iterators, here, for each collection. Let's take a look at these details.
Ruby each iteration:

Each iterator returns all the elements or hashes of an array.
Grammar:

Collection.each do |variable|
  Code End


Code that executes for each element in the collection. Here the collection may be an array or a ruby hash.
Example:

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

You always associate each iteration with the block. It returns each value of the array, blocks by block. The value is stored in the variable i and then displayed on the screen.
Ruby Collect iterations:

The collected iterator returns all the elements of a collection.
Grammar:

Collection = Collection.collect

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

#!/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 collection method is not the correct way to do the replication between the arrays. There is another method called cloning, which should be replicated to another array using one array.

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

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