tags:

views:

208

answers:

3

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

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

}
+13  A: 
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
Eimantas
A: 
['foo', 'bar', 'baz'].each_with_index {|j, i| puts "#{i} #{j}"}
S.Mark
+1  A: 
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

EmFi