0
0
Rubyprogramming~5 mins

Each as the primary iterator in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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
end
This 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}"
end
Click 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?
AThe entire array
BThe index of each element
CNothing
DEach element of the array
What will this code print?<br>
["a", "b", "c"].each { |x| puts x.upcase }
AA B C
Ba b c
Cabc
DError
When using each on a hash, what does the block receive?
ABoth key and value as two block parameters
BOnly the values
COnly the keys
DAn array of keys
What does each return after finishing iteration?
AThe last element processed
BThe original collection
Cnil
DThe number of elements
Which of these is true about each in Ruby?
AIt modifies the original collection
BIt returns a new array
CIt is the primary iterator method
DIt only works with arrays
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.