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更改哈希的键值的主要内容,如果未能解决你的问题,请参考以下文章

Java标准库中的键值,键值类[重复]

如何获取自己键盘上按键的键值(KeyCode)

如何从哈希图中找到最高的键值

雷林鹏分享:Ruby 哈希(Hash)

c++中map是有序的吗

从 Ruby 哈希中转移一个特定的匹配键值对