如何在Ruby中更改哈希的键值对?



我有一个返回数组和散列的查询。

我如何更改哈希并添加一个新的键值对: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}}

似乎响应是一个[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}, ...]

使用#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}构造Hash

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}}