In Ruby While loops are one of the ways we loop through a set of data in an array. A simple explanation is that while condition do something. While the provided variable such as count, or index is less than a provided number, keep looping through the array. Once count is equal to the length of our array, the looping process will stop on line 3. Without a condition for our while loop we could end up with an infinite loop, which will break our program
First example:
array = [1,2,3,4,5,6,7,8,9]
count = 0
while count < array.size do #while our provided variable count is less than array size
puts array[count]
count += 1
end
Second example:
array = [1,2,3,4,5,6,7,8,9]
count = 0
while count < array.size do
if array[count] % 2 == 0
puts array[count]
end #if statements written like this always require an end
count += 1
end
The first example will output the values of the array through puts on line 4 without any filter or change to the number. The second example is using an if statement to on line 4 to check if the number is even. Only IF the number is even will it be given as an output through puts on line 5.
In both examples count is used to keep the loop going as long as the array. This is why we use array.size (same as array.length) as the value count needs to be less than. But could there be an easier way? Enter the. each method. .each is a built in ruby method which loops (or iterates) through an array the same way the above while loop does, without setting up a counter.
Lets try these examples again with .each:
First example:
array = [1,2,3,4,5,6,7,8,9]
array.each do |number|
puts number
end
Second example:
array = [1,2,3,4,5,6,7,8,9]
array.each do |number|
if number % 2 == 0
puts number
end
end
Examples will have the same output as on top with much less code. We use number as a variable inside our || replacing array[count].
If we would like to shorten it even further we can replace do and end with {} also known as curly brackets.
First example:
array = [1,2,3,4,5,6,7,8,9]
array.each{ |number| puts number}
Second example:
array = [1,2,3,4,5,6,7,8,9]
array.each{ |number| if number % 2 == 0
puts number
end}
To shorten our if statement to just one line we can even do:
array.each{|number| puts number if number % 2 == 0}
Astute readers will notice we did not need an end for this kind of if statement!
To eliminate our if statement all together we can use .select. .select is similar to the while loops above as it loops or iterates through an array. The difference with. select is that it selects the values in that array that match the condition stated in our curly brackets.
For example:
array = [1,2,3,4,5,6,7,8,9]
array.select do |number|
number % 2 == 0
end
OR
array = [1,2,3,4,5,6,7,8,9]
array.select{|number| number % 2 == 0}
As you can see, .select iterates though our array and returns only the values that pass our conditional. Exactly the same as our if statements above with far less code.