×

ruby · level 3 · unit 2 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.