7 tips for Ruby iterators sharing _ruby topics

Source: Internet
Author: User

Ruby, which absorbs Perl's regular expressions and Python's readability, is a very human and flexible way to count values, which can be illustrated here:
First , print 7 times "Hello,world", as follows:

Copy Code code as follows:

7.times{puts "Hello,world"}
#在这里, puts's role is equivalent to print+ "\ n"

Second, print 1 in turn. 9, there are more methods in Ruby, which are implemented in simpler ways, as follows:
Copy Code code as follows:

(1..9). each{|i| Print I, ""}

Third, print 1. A number smaller than 7 in 9, as follows:
Copy Code code as follows:

1.upto (9) {|i| print I, "" If I < 7}

four, from 10 to 2 value, and then minus 1 processing, as follows:
Copy Code code as follows:

10.downto (2) Do |i|
Print I, ""
End

v. 1-9 each number in turn *2, and then enter the results as follows:
Copy Code code as follows:

A = 1..9
b = a.collect{|i| I*2}
P b[0..8]

print out elements that are divisible by 3 in the [1..100] array, as follows:
Copy Code code as follows:

A = (1..100). to_a
P a.select{|i| I%3 = = 0}

seven, from 3 to 19, and then add 3 processing, as follows:
Copy Code code as follows:

3.step (19,3) do |i|
Print I, ""
End

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.