Recall & Review
beginner
What does the
map method do in Ruby?The
map method takes each element of a collection, applies a block of code to it, and returns a new array with the transformed elements.Click to reveal answer
beginner
What is the difference between
map and each in Ruby?map returns a new array with transformed elements, while each simply iterates over elements without changing or returning a new array.Click to reveal answer
beginner
How do you use
map to square each number in an array [1, 2, 3]?You write: <br>
[1, 2, 3].map { |n| n * n } which returns [1, 4, 9].Click to reveal answer
intermediate
Can
map be used with hashes in Ruby?Yes,
map can be used with hashes. It transforms each key-value pair and returns an array of results. To get a hash back, you can use map.to_h.Click to reveal answer
intermediate
What happens if you use
map without a block?If you call
map without a block, it returns an Enumerator, which you can later use to chain or pass a block.Click to reveal answer
What does
[1, 2, 3].map { |x| x + 1 } return?✗ Incorrect
The
map method adds 1 to each element, returning [2, 3, 4].Which method returns a new array with transformed elements?
✗ Incorrect
map returns a new array with each element transformed by the block.What type of object does
map return when called without a block?✗ Incorrect
Without a block,
map returns an Enumerator.How can you convert the result of
map on a hash back to a hash?✗ Incorrect
You use
.to_h to convert an array of key-value pairs back to a hash.What will
[1, 2, 3].map { |n| n * 2 } output?✗ Incorrect
Each element is multiplied by 2, so the result is [2, 4, 6].
Explain how the
map method works in Ruby and give a simple example.Think about changing each item in a list and getting a new list back.
You got /3 concepts.
Describe the difference between
map and each in Ruby.One changes the collection, the other just looks at each item.
You got /4 concepts.