Syntax for a for loop in ruby

前端 未结 10 1033
梦如初夏
梦如初夏 2020-12-02 07:20

How do I do this type of for loop in Ruby?

for(int i=0; i
相关标签:
10条回答
  • 2020-12-02 07:47

    I keep hitting this as a top link for google "ruby for loop", so I wanted to add a solution for loops where the step wasn't simply '1'. For these cases, you can use the 'step' method that exists on Numerics and Date objects. I think this is a close approximation for a 'for' loop.

    start = Date.new(2013,06,30)
    stop = Date.new(2011,06,30)
    # step back in time over two years, one week at a time
    start.step(stop, -7).each do |d| 
        puts d
    end
    
    0 讨论(0)
  • 2020-12-02 07:48
    ['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
    
    0 讨论(0)
  • 2020-12-02 07:50

    To iterate a loop a fixed number of times, try:

    n.times do
      #Something to be done n times
    end
    
    0 讨论(0)
  • 2020-12-02 07:50

    What? From 2010 and nobody mentioned Ruby has a fine for /in loop (it's just nobody uses it):

    ar = [1,2,3,4,5,6]
    for item in ar
      puts item
    end
    
    0 讨论(0)
提交回复
热议问题