Recall & Review
beginner
What does the
each method do in Ruby?The
each method goes through each item in a collection like an array or hash, one by one, and runs the code inside the block for each item.Click to reveal answer
beginner
How do you write a simple
each loop for an array [1, 2, 3]?You write: <br>
[1, 2, 3].each do |number| puts number endThis prints each number on its own line.
Click to reveal answer
intermediate
Can
each be used with hashes? How?Yes! You can use
each with hashes to get both key and value. For example:<br>{a: 1, b: 2}.each do |key, value|
puts "#{key}: #{value}"
endClick to reveal answer
intermediate
What is the return value of
each?The
each method returns the original collection it was called on, unchanged.Click to reveal answer
beginner
Why is
each called the primary iterator in Ruby?Because
each is the most common and basic way to loop through collections in Ruby. Many other methods build on or use each internally.Click to reveal answer
What does the
each method yield to the block when used on an array?✗ Incorrect
The
each method passes each element of the array one by one to the block.What will this code print?<br>
["a", "b", "c"].each { |x| puts x.upcase }✗ Incorrect
The code prints each letter in uppercase on its own line: A B C.
When using
each on a hash, what does the block receive?✗ Incorrect
The block receives two parameters: the key and the value for each pair.
What does
each return after finishing iteration?✗ Incorrect
each always returns the original collection it was called on.Which of these is true about
each in Ruby?✗ Incorrect
each is the primary iterator because it is the basic way to loop through collections.Explain how the
each method works in Ruby and give an example with an array.Think about how you tell Ruby to do something for every item in a list.
You got /4 concepts.
Describe how you use
each with a hash and what the block receives.Remember a hash has pairs, so the block gets two things.
You got /3 concepts.