Andrew Walters8,876 Points
What are the benefits to Iterations with Each compared to (while) loops?
Just curious, if (in the example) using a while loop and using iterations with each gives us the same result, why is it beneficial to use one over the other? Could you give me any real world application examples? Thanks
Andrew Stelmach12,377 Points
You can use
each iterations for the same thing, but there are things you can do with
while that you can't do with
each. So you can use either thing to, for example, iterate over every element in an array.
each will always 'do something' for every single element of whatever you are iterating over, UNLESS you use the handy
array = ["Andy", "Bob", "Chris", "Paul"] answer = "" array.each do |name| answer = gets.chomp break if answer == name end
So, we do have a way to halt an
while will break out and cease an iteration when a certain condition is met by default:
array = ["Andy", "Bob", "Chris", "Paul"] answer = "" i = -1 while array[i] != answer do i += 1 answer = gets.chomp end
However, you could say that the above is not as clean nor readable as the first example.
However, you couldn't do something like the following with
name = "" while name != "Andy" do name = gets.chomp end
array =  while array.length < 5 do puts "Enter an item" item = gets.chomp array << item end
until is probably more readable though in this case:
array =  until array.length == 5 do puts "Enter an item" item = gets.chomp array << item end
Cheers! Writing this made me realise a couple of things too.