rubyclassputsruby-hash

How to display multiple items using puts?


I have written a Travel App with Tour Items and I'm trying to display the order at the end.

When I use puts @order_items I get {"SevendaySurfSportTour"=>2} for two tours.

I would like it to display 2 SevendaySurfSportTour at the end. But I don't know how, any help would be good?

class TourOrder
    def initialize
        @order_items = Hash.new(0)
    end
    def add_item(name, quantity)
        @order_items[name] += quantity
    end
    def get_items
        return @order_items
    end

    def display
        puts "Thank you for coming!"
        puts @order_items
    end
end

Solution

  • @order_items is a hash and what has printed out if the string representation of such a hash. When you want to format the output differently, then you have to implement that on your own – for example like this:

    def display
      puts "Thank you for coming!"
    
      @order_items.each do |name, quantity|
        puts "#{quantity} #{name}"
      end
    end