ruby · level 2 · unit 2 · lesson 1
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
changes every item and hands back a new array.
Arrays and hashes share a toolbox of methods called . You know one already: .each. This unit adds more, starting with .map. It runs the block on every item and collects each answer into a brand new array.
A short block can go in curly brackets instead of do and end: { |price| price * 2 }. Use curly brackets for one line, and do … end for longer blocks.
.map never changes the original array. Keep the result in a variable if you want to use it later.
prices = [2, 5, 3]
doubled = prices.map { |price| price * 2 }
p doubled
p prices
names = ["ada", "bo"]
p names.map { |name| name.upcase } The last line of the block is the answer that goes into the new array.
guess first
Shout every name. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
pets = ["rex", "tom", "kit"]
loud = pets.map { |pet| pet.upcase + "!" }
p loud
p pets.length
your turn
Your turn. Put the café prices up.
Choose how many pounds to add to every price, then press run to see the new price labels.
fix it
Nothing got doubled. Can you fix it?
- The output is the same as the start. Does
.mapchange the array it is called on? .maphands back a new array, but line 2 throws it away. Keep it in a variable.- Change line 2 to scores = scores.map { |score| score * 2 }, then press run.
nailed it
you changed a whole array at once. :D
.mapruns a block on every item and collects the answers.- It makes a new array and leaves the original alone.
- Use curly brackets for one-line blocks.
new words in your collection
- Enumerable
- map
This lesson isn’t saved. A free account remembers every lesson you finish.