0

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.

sdawes
  • 631
  • 1
  • 7
  • 15
  • You have `[[..]]`, so `@menu[0].each {..` will work. What you think is `Hash`, they are actually `Dish` object, which is `AR` object. – Arup Rakshit Jun 04 '16 at 19:17
  • cheers for that help, it didn't unfortunately, but that may be because I needed to called dish.name and dish.price rather than trying the code as was, but just adding the [0] to it. Cheers though! – sdawes Jun 04 '16 at 19:29
  • No. the error was from `@menu.each { |hash| `, what you think here a `hash` is the inner `Array`. And on that you called `[:name]` and that throws error. So `@menu[0].each { |hash| puts "Item: #{hash[:name]. Price: £#{hash[:price]}" }` will work too. – Arup Rakshit Jun 04 '16 at 19:34

1 Answers1

3

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}" }
rootatdarkstar
  • 1,486
  • 2
  • 15
  • 26
  • Amazing, that worked perfectly, thanks for the very quick reply, you have just saved me hours of more trial and error. – sdawes Jun 04 '16 at 19:28