Is there a Ruby version of for-loop similar to the one on Java/C++? Is there a Ruby version of for-loop similar to the one on Java/C++? ruby ruby

Is there a Ruby version of for-loop similar to the one on Java/C++?


Ruby tends to use iterators rather than loops; you can get all the function of loops with Ruby's powerful iterators.

There are several choices to do this, let's assume you have an array 'arr' of size 1000.

1000.times {|i| puts arr[i]}0.upto(arr.size-1){|i| puts arr[i]}arr.each_index {|i| puts arr[i]}arr.each_with_index {|e,i| puts e} #i is the index of element e in arr

All these examples provide the same functionality


Yes you can use each_with_index

collection = ["element1", "element2"]collection.each_with_index {|item,index| puts item; puts index}

the 'index' variable gives you the element index during each iteration


How about step?

0.step(1000,2) { |i| puts i }

is equivalent to:

for (int i=0; i<=1000; i=i+2) {    // do stuff}