Introduction to the iterator IN Ruby

Source: Internet
Author: User

Each

The simplest iterator is to access all elements collected continuously.

 [1,3,5,7,9].each { |i| puts i }

 

Output result:

1

3

5

7

9

The unique function is to implement the for loop of the Ruby language. Because the built-in loop primitives in Ruby only include while and. For is just a syntax block. For example:

for song in songlist song.playend

 

Ruby will use the each iterator to convert:

songlist.each do |song| song.playend

Collect

It obtains each element from the collection and passes it to the block. The result returned by block is used to generate a new array, for example:

["H", "A", "L"].collect {|x| x.succ}

 

Output result:

["I", "B", "M"]

Inject

Although the name is not easy to understand, it is also a useful iterator that allows you to traverse all the members of a mobile phone to accumulate a value. For example:

[1,3,5,7].inject(0) {|sum,element| sum+element} --> 16[1,3,5,7].inject(1) {|product,element| product*element} –> 105
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.