0
0
Rubyprogramming~5 mins

Map/collect for transformation in Ruby - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
A[2, 3, 4]
B[1, 2, 3]
C[1, 4, 9]
DAn error
Which method returns a new array with transformed elements?
Aeach
Bmap
Cselect
Ddelete
What type of object does map return when called without a block?
AArray
BNil
CHash
DEnumerator
How can you convert the result of map on a hash back to a hash?
AUse <code>.to_a</code>
BUse <code>.join</code>
CUse <code>.to_h</code>
DUse <code>.flatten</code>
What will [1, 2, 3].map { |n| n * 2 } output?
A[2, 4, 6]
B[1, 2, 3]
C[3, 4, 5]
DAn error
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.