Syntax for a for loop in ruby

前端 未结 10 1032
梦如初夏
梦如初夏 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:30

    If you don't need to access your array, (just a simple for loop) you can use upto or each :

    Upto:

    1.9.3p392 :030 > 2.upto(4) {|i| puts i}
    2
    3
    4
     => 2 
    

    Each:

    1.9.3p392 :031 > (2..4).each {|i| puts i}
    2
    3
    4
     => 2..4 
    
    0 讨论(0)
  • 2020-12-02 07:35
    array.each do |element|
      element.do_stuff
    end
    

    or

    for element in array do
      element.do_stuff
    end
    

    If you need index, you can use this:

    array.each_with_index do |element,index|
      element.do_stuff(index)
    end
    
    0 讨论(0)
  • 2020-12-02 07:35

    Ruby's enumeration loop syntax is different:

    collection.each do |item|
    ...
    end
    

    This reads as "a call to the 'each' method of the array object instance 'collection' that takes block with 'blockargument' as argument". The block syntax in Ruby is 'do ... end' or '{ ... }' for single line statements.

    The block argument '|item|' is optional but if provided, the first argument automatically represents the looped enumerated item.

    0 讨论(0)
  • 2020-12-02 07:39

    The equivalence would be

    for i in (0...array.size)
    end
    

    or

    (0...array.size).each do |i|
    end
    

    or

    i = 0
    while i < array.size do
       array[i]
       i = i + 1 # where you may freely set i to any value
    end
    
    0 讨论(0)
  • 2020-12-02 07:40
    limit = array.length;
    for counter in 0..limit
     --- make some actions ---
    end
    

    the other way to do that is the following

    3.times do |n|
      puts n;
    end
    

    thats will print 0, 1, 2, so could be used like array iterator also

    Think that variant better fit to the author's needs

    0 讨论(0)
  • 2020-12-02 07:45
    array.each_index do |i|
      ...
    end
    

    It's not very Rubyish, but it's the best way to do the for loop from question in Ruby

    0 讨论(0)
提交回复
热议问题