Iterations Flashcards
What would the following code show?
basket = [“apple 1”,”apple 2”,”apple 3”,”apple 4”,”apple 5”,”apple 6”,”apple 7”,”apple 8”,”apple 9”,”apple 10”]
basket.each do |apple|
puts “Taking out #{apple}”
end
"Taking out apple 1" "Taking out apple 2" "Taking out apple 3" "Taking out apple 4" "Taking out apple 5" "Taking out apple 6" "Taking out apple 7" "Taking out apple 8" "Taking out apple 9" "Taking out apple 10"
What is the difference between looping and iteration.
Looping is a construct that tells your program to run a certain amount of times until a condition has been met.
Iteration is a way to operate on a collection object, like an array and do something with each element in that collection.
What would the following code show?
primary_colors = [“Red”, “Yellow”, “Blue”]
primary_colors.each do |color|
puts “Primary Color #{color} is #{color.length} letters long.”
end
“Primary Color Red is 3 letters long.”
“Primary Color Yellow is 6 letters long.”
“Primary Color Blue is 4 letters long.”
What are | | used for in iterations?
| (also known as pipes) are used to hold arguments that are being passed into the iteration.
What would the following code look like?
brothers = [“Tim”, “Tom”, “Jim”]
brothers.each do |brother|
puts “Stop hitting yourself #{brother}!”
end
“Stop hitting yourself Tim!”
“Stop hitting yourself Tom!”
“Stop hitting yourself Jim!”
What is the shorter way of writing the following code using the { } syntax?
brothers = [“Tim”, “Tom”, “Jim”]
brothers.each do |brother|
puts “Stop hitting yourself #{brother}!”
end
brothers = [“Tim”, “Tom”, “Jim”]
brothers.each{|brother| puts “Stop hitting yourself #{brother}!”}
What is the differences between each iteration and collect/map iteration?
If you want the manipulated data returned back to you, use map or collect.
If you want to return the original array, use each.
What value will the following code return?
all_odd = [1,3].all? do |number|
number.odd?
end
True
What value will the following code return?
all_odd = [1,2,3].all? do |number|
number.odd?
end
False
How would you write an iteration that checks to see if all items are even numbers in the following array?
array = [1,2,3,4,5]
array.all? do |number|
number.even?
end
Should return false
What value will the following code return?
[1,3].none?{|i| i.even?}
True
How would you write an iteration that checks to see if none of the items are even numbers in the following array?
array = [1,3,5,7]
array.none? do |number|
number.even?
end
Should return true
What value will the following code return?
[1,2,100].any?{|i| i > 99}
True
How would you write an iteration that checks to see if any of the items are greater than 6 in the following array?
array = [1,3,5,7]
array.any?{|i| i > 6}
Should return true
What value will the following code return?
the_numbers = [4,8,15,16,23,42]
the_numbers.include?(42)
True