This is a Ruby Monk exercise and I'm having trouble wrapping my head around a particular concept.
For example, "soup bowl" = "soup bowl" + 1
wouldn't be valid, so why does @dishes_needed[a] = (@dishes_needed[a] || 0) + 1
work in the code below? Is it because they are variables and not objects? If so, why doesn't code a = (a||0)+1
work when I initially set a = "Soup"
:
class Dish
end
class Soup < Dish
end
class IceCream < Dish
end
class ChineseGreenBeans < Dish
end
class DeliveryTray
DISH_BOWL_MAPPING = {
Soup => "soup bowl",
IceCream => "ice cream bowl",
ChineseGreenBeans => "serving plate"
}
def initialize
@dishes_needed = {}
end
def add(dish)
a = DISH_BOWL_MAPPING[dish.class]
@dishes_needed[a] = (@dishes_needed[a] || 0) + 1
end
def dishes_needed
return "None." if @dishes_needed.empty?
@dishes_needed.map { |dish, count| "#{count} #{dish}"}.join(", ")
end
end
d = DeliveryTray.new
d.add Soup.new; d.add Soup.new
d.add IceCream.new
puts d.dishes_needed # should be "2 soup bowl, 1 ice cream bowl"