【问题标题】:Accessing hash values inside an array and moving them to a new array or hash using a loop [closed]访问数组内的哈希值并使用循环将它们移动到新数组或哈希[关闭]
【发布时间】:2013-11-23 18:23:55
【问题描述】:

所以我正在使用 Ruby 并尝试编写具有项目 sku/types/prices 的收银机,并且无法找出查询数组内的哈希以访问这些值并将它们添加到订单的最佳方法,假设订购了 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

【问题讨论】:

  • 如果您发布了有效的哈希定义会有所帮助。这是你走的最远的吗?

标签: ruby arrays methods hash


【解决方案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 查找商品,请尝试将其设为 Hash 而不是 Array:

@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

【讨论】:

  • 谢谢这真的很有帮助。非常感谢!
猜你喜欢
  • 2023-03-31
  • 2013-03-22
  • 2020-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-06
  • 1970-01-01
相关资源
最近更新 更多