英文:
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"}]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论