Mazeryt
Mazeryt

Reputation: 915

Ruby how each loop is executed?

I have issue with technically deep question about loops in ruby.

I have algorithm that is executed sequentially for array of Boolean values and operate on one data structures.

def function(boolean, data_structure)

The key point is that the order of execution is most important thing because expression

 function(true, data_structure);function(true, data_structure); function(false, data_structure)

will leave other result in data structure than expression

 function(true, data_structure);function(false, data_structure); function(true, data_structure)

I spent some time trying with each loop, but I didn't get any problems as other result in data structure due execution similar expression as follow

[true, true, false ....].each do |value| function(value, data_structure) end

My question: in default ruby configuration is my each loop is the same like followed for loop?

for i in 0..array.size do function(array[i], data_structure) end

Because each loop makes the code much clearer and easier to modify and I was thinking about leave each expression rather than using for loop. (Of course in my case I have a lot more code rather than calling only function()..)

Upvotes: 0

Views: 231

Answers (1)

user229044
user229044

Reputation: 239301

Yes, it's identical. It will loop through the elements of the array, in order.

Upvotes: 2

Related Questions