简体   繁体   中英

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()..)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM