Search code examples
arraysrubyiterationhash-of-hashes

How to iterate over an array of hashes which contain instantiated object information in Ruby?


I created a class called Dish, where I then created a number of menu objects, items for a menu containing name and price, the information which was obtained through the initialized method. when calling

chickenstew = Dish.new("Chicken Stew", 4.50)

I then added a number of these objects to an array contained in an instance variable @menu = [] of a new class, called Menu, using the method def add_to_menu and @menu << args. When I display the new menu array containing the individual objects, you obviously get the object information, in addition to the name and price info, as follows:

[[#<Dish:0x007f9662134818 @dish={:name=>"Chicken Stew", :price=>4.5}>,
  #<Dish:0x007f966206ec30 @dish={:name=>"Beef & Ale Pie", :price=>5.0}>,
  #<Dish:0x007f966101a7a8 @dish={:name=>"Chicken & Leek Pie", :price=>4.0}>,
  #<Dish:0x007f9662365420 @dish={:name=>"Vegetable Pie", :price=>3.5}>,
  #<Dish:0x007f96622de038 @dish={:name=>"Fish Pie", :price=>5.5}>,
  #<Dish:0x007f966224f068 @dish={:name=>"Chips", :price=>2.0}>,
  #<Dish:0x007f966222c1d0 @dish={:name=>"Mushy Peas", :price=>1.5}>]] 

My question is, how on earth do you iterate through this array of hashes, in order to extract just the name and price details, in order to puts this to the screen? I have tried @menu.each { |hash| puts "Item: #{hash[:name]. Price: £#{hash[:price]}" } but this obviously fails and I get no end of errors such as 'TypeError: no implicit conversion of Symbol into Integer'

Any help would be appreciated.


Solution

  • This is not a hash inside your array. This is object of Dish class, so:

    @menu.first.each { |dish| puts "Item: #{dish.name}. Price: £#{dish.price}" }