访问数组内的哈希值,并使用循环将它们移动到新数组或哈希

时间:2013-11-23 18:23:55

标签: ruby arrays methods hash

所以我正在使用Ruby并尝试编写具有项目sku /类型/价格的收银机,并且无法找出查询数组内部哈希以访问这些值并将其添加到订单的最佳方法,如果订购了5个小型和3个大型。任何人都可以帮忙建议如何解决这个问题?我可以编写显示/菜单界面我只是不知道最好/最简单的方法来搜索该数据,如果有人订购它然后将这些值移动到另一个哈希或数组,以便它将包含该客户的整个订单,然后可以最终总结所有订单的总数。

@sku_menu = [{Type => Small, SKU => 11, Price =>5.00},
            {Type => Medium, SKU 22 =>, Price => 7.50},
            {Type => Large, SKU => 33, Price => 9.75}]

\ n

1 个答案:

答案 0 :(得分:1)

首先,制作哈希符号的键,而不是常量。类型值相同:

@sku_menu = [
  { type: :small,  :sku => 11, price: 5.00 },
  { type: :medium, :sku => 22, price: 7.50 },
  { type: :large,  :sku => 33, price: 9.75 },
]

接下来,我们选择我们想要的值:

# Gives an array of just the 'large' items
larges = @sku_menu.select{ |hash| hash[:type]==:large }

# Gives just the hash with the desired SKU
sku22 = @sku_menu.find{ |hash| hash[:sku]==22 }

# Gives an array of hashes
expensive = @sku_menu.select{ |hash| hash[:price] > 7 }

# Gives an array of hashes with the specified SKUs
selected = @sku_menu.select{ |hash| [11,22].include?( hash[:sku] )  }

现在,如果您想通过SKU更容易找到项目,请尝试将其设为哈希而不是数组:

@sku_menu = {
  11 => { type: :small,  :sku => 11, price: 5.00 },
  22 => { type: :medium, :sku => 22, price: 7.50 },
  33 => { type: :large,  :sku => 33, price: 9.75 },
}

sku11 = @sku_menu[11]

有了这个,你仍然可以select所需的项目(但语法略有不同):

# Gives an array of just the 'large' items
larges = @sku_menu.values.select{ |hash| hash[:type]==:large }

# …alternatively
larges = @sku_menu.select{ |sku,hash| hash[:type]==:large }.values