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

dsf9zpds  于 2023-02-12  发布在  Ruby
关注(0)|答案(2)|浏览(141)

我有一个返回数组和散列的查询。
如何更改散列并向其添加新的键值对: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}}
mhd8tkvw

mhd8tkvw1#

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

xwmevbvl2#

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

相关问题