Ruby Loops & Iterators Flashcards
loop
loop takes a block, which is denoted by { … } or do … end. A loop will execute any code within the block (again, that’s just between the {} or do … end) until you manually intervene with Ctrl + c or insert a break statement inside the block, which will force the loop to stop and the execution will continue after the loop.
loop do
puts “This will keep printing until you hit Ctrl + c”
end
i = 0 loop do i += 1 puts i break # this will cause execution to exit the loop end
break
The break keyword allows us to exit a loop at any point, so any code after a break will not be executed. Note that break will not exit the program, but only exit the loop and execution will continue on from after the loop.
conditional_loop.rb
i = 0 loop do i += 2 puts i if i == 10 break # this will cause execution to exit the loop end end
next
We can use the keyword next to skip the rest of the current iteration and start executing the next iteration.
next_loop.rb
i = 0 loop do i += 2 if i == 4 next # skip rest of the code in this iteration end puts i if i == 10 break end end
while loop
A while loop is given a parameter that evaluates to a boolean (remember, that’s just true or false). Once that boolean expression becomes false, the while loop is not executed again, and the program continues after the while loop.
countdown.rb
x = gets.chomp.to_i
while x >= 0
puts x
x = x - 1
end
puts “Done!”
until loop
The until loop is simply the opposite of the while loop. You can substitute it in order to phrase the problem in a different way.
countdown.rb
x = gets.chomp.to_i
until x < 0
puts x
x -= 1
end
puts “Done!”
do/while loop
A do/while loop is very similar to a while loop, with the only difference being that the code within the loop gets executed one time, prior to the conditional check to see if the code should be executed. In a “do/while” loop, the conditional check is placed at the end of the loop as opposed to the beginning.
loop do puts "Do you want to do that again?" answer = gets.chomp if answer != 'Y' break end end
for loops
for loops are used to loop over a collection of elements. Unlike a while loop where if we’re not careful we can cause an infinite loop, for loops have a definite end since it’s looping over a finite number of elements. It begins with the for reserved word, followed by a variable, then the in reserved word, and then a collection of elements.
countdown3.rb
x = gets.chomp.to_i
for i in 1..x do
puts i
end
puts “Done!”
countdown4.rb
x = [1, 2, 3, 4, 5]
for i in x do
puts i
end
puts “Done!”
range
A range is a special type in Ruby that captures a range of elements. For example 1..3 is a range that captures the integers 1, 2, and 3.
Iterators
Iterators are methods that naturally loop over a given set of data and allow you to operate on each element in the collection.
each
each is a method used to iterate over each element.
practice_each.rb
names = [‘Bob’, ‘Joe’, ‘Steve’, ‘Janice’, ‘Susan’, ‘Helen’]
names.each { |name| puts name }
We have called the each method using the dot operator (.) on our array. What this method does is loop through each element in our array, in order, starting from ‘Bob’. Then it begins executing the code within the block. The block’s starting and ending points are defined by the curly braces {}. Each time we iterate over the array, we need to assign the value of the element to a variable. In this example we have named the variable name and placed it in between two pipes |. After that, we write the logic that we want to use to operate on the variable, which represents the current array element. In this case it is simply printing to the screen using puts.
block
A block is just some lines of code ready to be executed. When working with blocks there are two styles you need to be aware of. By convention, we use the curly braces ({}) when everything can be contained in one line. We use the words do and end when we are performing multi-line operations.
practice_each.rb
names = ['Bob', 'Joe', 'Steve', 'Janice', 'Susan', 'Helen'] x = 1
names.each do |name|
puts “#{x}. #{name}”
x += 1
end
Recursion
Recursion is another way to create a loop in Ruby. Recursion is the act of calling a method from within itself.
irb(main):001:0> def doubler(start) irb(main):002:1> puts start * 2 irb(main):003:1> end => :doubler irb(main):004:0> doubler(2) 4 => nil irb(main):005:0> doubler(4) 8 => nil irb(main):006:0> doubler(8) 16 => nil
You can do this much more simply using recursion. Take a look at this version of the method:
def doubler(start) puts start if start < 10 doubler(start * 2) end end