2013-03-30 4 views
12

私は逆の範囲が空の範囲に等しいので、私はそれは私に何を獲得しませんこのようRubyの特定のステップで逆の範囲を反復処理するにはどうすればよいですか?

(10..0).step(2){|v| puts v} 

を反復することはできません、この

(0..10).step(2){|v| puts v} 

のように繰り返すことができますが。もちろん、私はこの

10.downto(0){|v| puts v} 

のように後方に反復することができますが、この方法とdownto私はデフォルトの1 それは、非常に基本的な何かを除いて、他のステップを設定することはできませんので、私はへの組み込みの方法があるはずと仮定しますこれは私が知らないものです。

+0

あなたは '(0..10)。ステップのような何かを行うことができます(2).reverse'を実行しますが、 '(10..0).step(2)'からの出力が異なる場合には、いくつかのロジックを追加する必要があります。 – jvnill

+0

'(0..10).step(2).reverse'は無効です。 Rubyは次のように言っています: 'NoMethodError:#'のための未定義のメソッド 'reverse'。 –

答えて

20

は、なぜあなたは使用しないNumeric#step:ドキュメントから

Invokes block with the sequence of numbers starting at num, incremented by step (default 1) on each call. The loop finishes when the value to be passed to the block is greater than limit (if step is positive) or less than limit (if step is negative). If all the arguments are integers, the loop operates using an integer counter. If any of the arguments are floating point numbers, all are converted to floats, and the loop is executed floor(n + n*epsilon)+ 1 times, where n = (limit - num)/step. Otherwise, the loop starts at num, uses either the < or > operator to compare the counter against limit, and increments itself using the + operator.

 
irb(main):001:0> 10.step(0, -2) { |i| puts i } 
10 
8 
6 
4 
2 
0 
+1

ニース。私は別のやり方を見つけましたが、それほどエレガントではありません:(-10..0).step(2){| v | -1 * v} – user1887348

4

不要な値をスキップしてstepをエミュレートするのは非常に簡単です。このような何か:

10.downto(0).each_with_index do |x, idx| 
    next if idx % 3 != 0 # every third element 
    puts x 
end 
# >> 10 
# >> 7 
# >> 4 
# >> 1 
+0

条件を指定して実行している各ステートメントの要素をスキップしていて、それが間違っている場合、select: '10.downto(0).select.with_index {| x、idx | idx%3 == 0} .each {| x | puts x} ' – SamStephens

+0

@SamStephens:議論の余地があります。 –

+0

すべてですが、私はRubyの機能的コレクションベースの機能を使用する場合、機能的スタイルと命令的スタイルを混ぜるのではなく、それらを一貫して使用するべきだと主張します。 – SamStephens

関連する問題