Ruby: jak iterować w zakresie, ale w set increments?

Więc iteruję w takim zakresie:

(1..100).each do |n|
    # n = 1
    # n = 2
    # n = 3
    # n = 4
    # n = 5
end

Ale to, co chciałbym zrobić, to iterację do dziesiątek.

Więc zamiast zwiększyć n o 1, następny n faktycznie będzie 10, potem 20, 30, itd.

Author: Shpigford, 2010-12-03

4 answers

Zobacz http://ruby-doc.org/core/classes/Range.html#M000695 dla pełnego API.

Zasadniczo używasz metody step(). Na przykład:

(10..100).step(10) do |n|
    # n = 10
    # n = 20
    # n = 30
    # ...
end
 224
Author: Berin Loritsch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-12-03 14:15:18

Możesz użyć Numeric#step.

0.step(30,5) do |num|
  puts "number is #{num}"
end
# >> number is 0
# >> number is 5
# >> number is 10
# >> number is 15
# >> number is 20
# >> number is 25
# >> number is 30
 7
Author: Arup Rakshit,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-02-24 22:09:09
rng.step(n=1) {| obj | block } => rng

Iteruje przez rng, przekazując każdy n-ty element do bloku. Jeśli zakres zawiera liczby lub ciągi znaków, używana jest kolejność naturalna. W przeciwnym razie step wywołuje succ do iteracji przez elementy zakresu. Poniższy kod używa klasy Xs, która jest zdefiniowana w dokumentacji na poziomie klasy.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

Produkuje:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Odniesienie: http://ruby-doc.org/core/classes/Range.html

......

 5
Author: Jahan Zinedine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-05 10:31:19

Oto inny, być może bardziej znajomy sposób na zrobienie tego:

for i in (0..10).step(2) do
    puts i
end
 3
Author: justsomeguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-11 20:10:10