如何遍历Ruby中包含实例化对象信息的哈希数组?

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

我创建了一个名为 Dish 的 class,然后我在其中创建了一些菜单对象,菜单项包含名称和价格,这些信息是通过初始化方法获得的。打电话时

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

然后,我使用方法 def add_to_menu 和 [=15] 将这些对象中的一些添加到新 class 的实例变量 @menu = [] 中包含的数组中,该变量称为 Menu =].当我显示包含单个对象的新菜单数组时,您显然得到了对象信息,除了名称和价格信息,如下所示:

[[#<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}>]] 

我的问题是,您究竟如何遍历这个哈希数组,以便仅提取名称和价格详细信息,以便 puts 将其显示在屏幕上?我试过 @menu.each { |hash| puts "Item: #{hash[:name]. Price: £#{hash[:price]}" } 但这显然失败了,而且我没有结束诸如 'TypeError: no implicit conversion of Symbol into Integer'

之类的错误

如有任何帮助,我们将不胜感激。

这不是您数组中的散列。这是 Dish class 的对象,所以:

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