查找并替换特定的哈希值及其在数组中的值 [英] Find and replace specific hash and it's values within array
问题描述
在数组中查找特定散列并就地替换其值的最有效方法是什么,以便数组也被更改?
What is the most efficient method to find specific hash within array and replace its values in-place, so array get changed as well?
到目前为止,我已经得到了这段代码,但是在具有大量数据的实际应用程序中,这成为应用程序中最慢的部分,这可能会泄漏内存,因为当我在每个 websocket 上执行此操作时,无限内存会不断增长留言.
I've got this code so far, but in a real-world application with loads of data, this becomes the slowest part of application, which probably leaks memory, as unbounded memory grows constantly when I perform this operation on each websocket message.
array =
[
{ id: 1,
parameters: {
omg: "lol"
},
options: {
lol: "omg"
}
},
{ id: 2,
parameters: {
omg: "double lol"
},
options: {
lol: "double omg"
}
}
]
selection = array.select { |a| a[:id] == 1 }[0]
selection[:parameters][:omg] = "triple omg"
p array
# => [{:id=>1, :parameters=>{:omg=>"triple omg"}, :options=>{:lol=>"omg"}}, {:id=>2, :parameters=>{:omg=>"double lol"}, :options=>{:lol=>"double omg"}}]
推荐答案
这将在只循环一次记录后执行您的操作:
This will do what you're after looping through the records only once:
array.each { |hash| hash[:parameters][:omg] = "triple omg" if hash[:id] == 1 }
你总是可以扩展块来处理其他条件:
You could always expand the block to handle other conditions:
array.each do |hash|
hash[:parameters][:omg] = "triple omg" if hash[:id] == 1
hash[:parameters][:omg] = "quadruple omg" if hash[:id] == 2
# etc
end
而且它只会迭代元素一次.
And it'll remain iterating over the elements just the once.
也可能您更适合将数据调整为单个散列.一般来说,搜索散列比使用数组更快,特别是如果你有唯一标识符,就像这里一样.类似的东西:
It might also be you'd be better suited adjusting your data into a single hash. Generally speaking, searching a hash will be faster than using an array, particularly if you've got unique identifier as here. Something like:
{
1 => {
parameters: {
omg: "lol"
},
options: {
lol: "omg"
}
},
2 => {
parameters: {
omg: "double lol"
},
options: {
lol: "double omg"
}
}
}
这样,您只需调用以下代码即可实现您的目标:
This way, you could just call the following to achieve what you're after:
hash[1][:parameters][:omg] = "triple omg"
希望有所帮助 - 让我知道您的进展情况或有任何疑问.
Hope that helps - let me know how you get on with it or if you have any questions.
这篇关于查找并替换特定的哈希值及其在数组中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!