Syntax for a for loop in ruby

Viewed 122792

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

for(int i=0; i<array.length; i++) {

}
10 Answers
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
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

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

n.times do
  #Something to be done n times
end
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
Related