How to write negative loop in ruby like for(i=index; i >= 0; i --)

前端 未结 7 1354
滥情空心
滥情空心 2020-12-25 10:42

How can I write a loop in Ruby that counts down, similar to the following C-style for loop?

for (i = 25; i >= 0; i--) { 
    print i;
}


        
相关标签:
7条回答
  • 2020-12-25 11:05

    One way:

    25.downto(0) do |i|
      puts i
    end
    
    0 讨论(0)
  • 2020-12-25 11:08

    Try this:

    25.downto(0) { |i| puts i }
    
    0 讨论(0)
  • 2020-12-25 11:12

    Print reverse array elements:

    nummarray = [3,4,7,3,6,8]
    
    (numarray.length-1).downto(0){ |i| print numarray[i] }
    
    0 讨论(0)
  • 2020-12-25 11:13

    There are many ways to perform a decrementing loop in Ruby:

    First way:

    for i in (10).downto(0)
      puts i
    end
    

    Second way:

    (10).downto(0) do |i|
      puts i
    end
    

    Third way:

    i=10;
    until i<0
      puts i
      i-=1
    end
    
    0 讨论(0)
  • 2020-12-25 11:19

    downto is fine, but there is also the more generic step.

    25.step(0, -1){|i| puts i}
    
    0 讨论(0)
  • 2020-12-25 11:19

    Just in case you are working with a range already:

    rng = 0..6
    rng.reverse_each { |i| p i }
    

    EDIT - more succinctly:

    puts(rng.to_a.reverse)
    
    0 讨论(0)
提交回复
热议问题