What is the most efficient method to find specific hash within array and replace its values in-place, so array get changed as well?
I\'ve got this code so far, but in a
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.