7 tips for Ruby iterators and ruby7 skills

Source: Internet
Author: User

7 tips for Ruby iterators and ruby7 skills

Ruby absorbs the regular expressions of Perl and the readability of Python, so the counting value method is very user-friendly and flexible. Here we can illustrate it as an example:
1. Print "hello, world" 7 times, as shown below:
Copy codeThe Code is as follows:
7. times {puts "hello, world "}
# Here, puts serves the same purpose as print + "\ n"

2. Print in sequence, and there are more methods in ruby. Here we use a simple method to implement it, as shown below:
Copy codeThe Code is as follows:
(1 .. 9). each {| I | print I ,""}

3. Print a value smaller than 7 in 1.9, as shown below:
Copy codeThe Code is as follows:
1. upto (9) {| I | print I, "" if I <7}

4. cycle from 10 to 2, and subtract 1 for processing, as shown below:
Copy codeThe Code is as follows:
10. downto (2) do | I |
Print I ,""
End

5. Set each number from 1 to 9 to 2 in sequence, and then enter the result as follows:
Copy codeThe Code is as follows:
A = 1 .. 9
B = a. collect {| I * 2}
P B [0 .. 8]

6. Print the elements in the [1 .. 100] array that can be divisible by 3, as shown below:
Copy codeThe Code is as follows:
A = (100). to_a
P a. select {| I % 3 = 0}

7. cycle from 3 to 19 and add 3 for processing in sequence, as shown below:
Copy codeThe Code is 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.