将哈希值插入到另一个 Ruby 哈希中,不使用外部括号。

huangapple go评论57阅读模式
英文:

Insert hash values into another hash in ruby without outer parentesis

问题

我有一个模板中的以下数据结构:

[
{
geometry: {
type: geometry, coordinates: coordinates
},
}
]


然后我有一个选项哈希,看起来像这样:

options = { label: "Hot Chicken Takeover",
tooltip: "5 stars",
color: "#0090ff" }


我该如何将options中的键值对添加到上面的数组中,使其看起来像这样:

[
{
geometry: {
type: geometry, coordinates: coordinates
},
label: "Hot Chicken Takeover",
tooltip: "5 stars",
color: "#0090ff"
}
]


在Ruby中是否有一种“展开”哈希的方法?
英文:

I have the following data structure in one of my templates:

[
  {
    geometry: {
      type: geometry, coordinates: coordinates
    },
  }
]

and then i have an options-hash that looks like this:

options = { label: "Hot Chicken Takeover",
            tooltip: "5 stars",
            color: "#0090ff" }

how can i add the key-value pairs from options into the array above so that it looks like this:

[
  {
    geometry: {
      type: geometry, coordinates: coordinates
    },
    label: "Hot Chicken Takeover",
    tooltip: "5 stars",
    color: "#0090ff"
  }
]

is there any way to "flatten" a hash in ruby?

答案1

得分: 1

在下面的示例中,我们首先使用data[0]访问数据数组的第一个元素。然后,我们使用merge方法将options哈希合并到geometry哈希中。得到的哈希值被重新赋给data[0]

data = [{ geometry: { type: 'geometry', coordinates: [1, 2] }}]

options = { label: "Hot Chicken Takeover",
            tooltip: "5 stars",
            color: "#0090ff" }

data[0] = data[0].merge(options)

puts data.inspect

输出

[{:geometry=>{:type=>"geometry", :coordinates=>[1, 2]}, :label=>"Hot Chicken Takeover", :tooltip=>"5 stars", :color=>"#0090ff"}]
英文:

In the given below example, we first access the first element of the data array using data[0]. We then merge the options hash into the geometry hash using merge method. The resulting hash is assigned back to data[0].

data = [{ geometry: { type: 'geometry', coordinates: [1, 2] }}]

options = { label: "Hot Chicken Takeover",
            tooltip: "5 stars",
            color: "#0090ff" }

data[0] = data[0].merge(options)

puts data.inspect

output

[{:geometry=>{:type=>"geometry", :coordinates=>[1, 2]}, :label=>"Hot Chicken Takeover", :tooltip=>"5 stars", :color=>"#0090ff"}]

huangapple
  • 本文由 发表于 2023年4月19日 23:30:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76056330.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定