Loops and iterators Flashcards
What is a loop?
The repetitive execution of a piece of code for a given amount of repetitions or until a certain condition is met
What is the key combination to manually intervene a loop?
Ctrl + c
Create an eternal loop!
Loop do
puts “this will keep printing until ctrl + c is hit”
end
How do you quit a loop internally? (+example)
With the “break” keyword (note that it only breaks out of the loop, not of the whole program)
e.g.
i = 0 loop do i += 2 puts i if i == 10 break end end
How can you skip an operation in a loop?
With the “next” keyword
e.g.
i = 0 loop do i += 2 if i == 4 next end puts i if i == 10 break end end
How does a do/while loop work? (+example)
Do/while loop goes on until the condition is not met, but the code gets executed at least once e.g. loop do puts "Do you wanna do it again" answer = gets.chomp if answer != "Y" break end end
(The loop keeps going as long as your input is “Y”, and breaks if it’s anything else)
What is the difference between a “while” and a “for” loop?
“for” loop returns the collection of elements after it executes, whereas “while” loop returns “nil”
How does “while” loop work? (+example)
A while loop is given a parameter that evaluates to a boolean. If false, the while loop is not executed again, and the program continues after the while loop.
e.g.
x = gets.chomp
while x > 0
puts x
x += 1
end
puts “Done!”
Describe the “unless” loop with an example!
It’s another way to express things
It is the opposite of the “while” loop.
e.g.
x = gets.chomp
until x < 0
puts 0
x -= 1
end
puts “Done!”
What are “for” loops used for?
For loops are used to loop over a collection of elements.
They have a definite end since it’s looping over a finite number of elements.
e.g.
x = [1, 2, 3, 4, 5]
for i in x do
puts i
end
puts “Done again!”
Use “next” in a conditional “while” loop!
x = 0
while x <= 10 if == 3 x += 1 next elsif x.odd? puts x end x += 1 end
=> 1, 5, 7, 9
Use “break” in a conditional “while” loop!
x = 0
while x <= 10 if x == 7 break elsif x.odd? puts x end x += 1 end
=>1, 3, 5
What are iterators?
Methods that naturally loop over a given set of data and allow you to operate on each element in the collection.
Iterate over an array with the “each” method!
fruit = [“banana”, “kiwi”, “apple”, “orange”, “peach”]
fruit.each {|yummy| puts yummy}
=> banana kiwi apple orange peach
How can you design the starting and ending points of blocks?
Either with {} in case of a one line expression and “do” “end” in case of multiple line expression