Loops Flashcards
1
Q
Create a while loop which will loop through a deck of cards until it finds a spade.
A
cards = ["Diamond", "Heart", "Club", "Diamond"] current_card = "Heart"
while current_card != "Spade" puts current_card current_card = cards[rand (0..3)] end puts "OMG a SPADE!"
2
Q
Create a quick example of a until loop
A
counter = 1
until counter == 10
end
3
Q
Create a for loop which will print the numbers 1 to 10 (including 10) to the console.
A
for num in (1..10)
puts num
end
4
Q
Print the numbers 20 through 0 to the console using a iterator method. Also create a iterator method that will print the numbers 1 to 5 to the console.
A
j = 21 loop do j -= 1 puts "#{j}" break if j <= 0 end
j = 0 loop do j += 1 puts "#{j}" break if j >= 5 end
5
Q
How would you use a iterator method to print the numbers 1 to 5 excluding the even numbers.
A
j = 0 loop do j += 1 puts "#{j}" end