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