Ruby更改哈希的键值
Posted
技术标签:
【中文标题】Ruby更改哈希的键值【英文标题】:Ruby change key value of hash 【发布时间】:2021-12-07 12:03:02 【问题描述】:我有一个返回这个数组和哈希的查询。如何更改哈希并向其添加新的键值对 import_id: 1, cost: 0
或者我可以在查询中执行 map
吗?
查询
name = Store.joins(:paid => :supply).group(:name).select("supply.name").where("stores.identifier IN (?) ", tids).pluck(:supply_id, :name)
数组
[[258, "Square"], [245, "App"]]
当我将其转换为哈希时,它会返回
258=>"Square", 245=>"App"
想要的输出
supply_id: 258, name: "Square", import_id: 1, cost: 0, supply_id: 245, name: "App", import_id: 1, cost: 0
【问题讨论】:
【参考方案1】:看起来响应是[supply_id, name]
对的数组。您可以使用适当的符号键轻松解构数组并将数据重组为哈希。
array = [[258, "Square"], [245, "App"]]
array.map do |(id, name)|
supply_id: id, name: name, import_id: 1, cost: 0
end
# [:supply_id=>258, :name=>"Square", :import_id=>1, :cost=>0, ...]
【讨论】:
【参考方案2】:使用#select
代替#pluck
并调用.as_json
或.map(&:attributes)
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name).as_json
# [supply_id: 258, name: "Square", supply_id: 245, name: "App"]
或
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name).map(&:attributes)
# [supply_id: 258, name: "Square", supply_id: 245, name: "App"]
或者你可以构造带有import_id: 1, cost: 0
的哈希
Store.joins(:paid => :supply).group(:name)
.select("supply.name").where("stores.identifier IN (?) ", tids)
.select(:supply_id, :name)
.map |e| supply_id: e.supply_id, name: e.name, import_id: 1, cost: 0
# [supply_id: 258, name: "Square", import_id: 1, cost: 0, supply_id: 245, name: "App", import_id: 1, cost: 0]
或
您可以在哈希生成步骤中使用Hash#merge
来包含import_id: 1, cost: 0
hash.merge(import_id: 1, cost: 0)
# To achieve: supply_id: 258, name: "Square", import_id: 1, cost: 0, supply_id: 245, name: "App", import_id: 1, cost: 0
【讨论】:
以上是关于Ruby更改哈希的键值的主要内容,如果未能解决你的问题,请参考以下文章