Iterators Flashcards
1
Q
Why do we need “redo” operator?
A
The redo keyword allows you repeat the last iteration inside the loop.
10.times do |i|
puts “Iteration #{i}”
redo if i > 2
end
# infinity loop # Iteration 3 # Iteration 3 ...
2
Q
How to write FOR iterator?
A
for i in [1,2,3] do
p i
end
# 1 # 2 # 3
3
Q
Why do we need “retry” operator?
A
The retry keyword allows retrying a piece of code in a block.
begin p 'hello' raise rescue retry end
The following code will return ‘hello’ in infinity loop.
4
Q
What is case patter matching?
A
response = { error: 'Bad Gateway', code: 502 } case response in { data: data, code: code } puts "Success #{data}, Code: #{code}" in { error: error, code: code } puts "Error: #{error}, Code: #{code}" end
Error: Bad Gateway, Code: 502