ruby · level 3 · unit 2 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Include , and one each buys dozens of methods.
Your playlist has each, but no map, select or sort_by. You could write them all yourself, or you can mix in Enumerable, the module behind the searching and sorting you know from arrays. Every Enumerable method is built on top of each, so that is all your class needs.
Add include Enumerable and select, map, count, first, include?, sum, sort_by and friends all work. and its partner max_by find the item whose block answer is smallest or largest, like the cheapest dish on a menu. Most of them hand back an ordinary array.
class Menu
include Enumerable
def initialize(dishes)
@dishes = dishes
end
def each
@dishes.each { |dish| yield dish }
end
end
menu = Menu.new([{ name: "Soup", price: 4 }, { name: "Curry", price: 9 }, { name: "Pie", price: 7 }])
puts menu.min_by { |dish| dish[:price] }[:name]
p menu.select { |dish| dish[:price] > 5 }.map { |dish| dish[:name] }
puts menu.sum { |dish| dish[:price] } Enumerable is the same module that gives arrays and hashes their power tools, so everything you know carries over.
guess first
The garden never defines sort. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class Garden
include Enumerable
def each
yield "rose"
yield "tulip"
yield "daisy"
end
end
garden = Garden.new
p garden.sort
p garden.include?("tulip")
p garden.first(2)
your turn
Your turn. Give the results table superpowers.
In the first blank, mix in the module that builds methods on each. In the second, pick the score that counts as a pass.
fix it
The basket cannot add up. Fix the class.
- The error mentions a method called
each. Does the class have one? - Enumerable builds every method on a method named exactly
each, nothing else. - Rename
each_pricetoeachon line 6, then press run.
nailed it
your class joined the enumerable family. :D
include Enumerableadds dozens of methods to any class.- It only needs one method, named exactly
each. min_byandmax_byfind the smallest or largest by your rule.
new words in your collection
- Enumerable
- min_by
This lesson isn’t saved. A free account remembers every lesson you finish.