我有一个复杂的数据结构(散列数组的多个级别)。我想查找并更新一个特定值。但是,detect
似乎没有将引用传递给我要更新的数据结构中的位置。我可以使用each
或进行编码,each_with_object
但是当我想在第一个匹配项中停止时,它将遍历所有数据。在我的实际程序中,"mymouse"
和485
是代表这些值的变量。
哪个单行命令可以更新该条目?为什么在修改数据方面detect
不起作用each{}
?我希望这会起作用,因为Ruby是按引用传递的。
mynew = [{:mouse=>{:cat=>[485, 2, 10, 10, 10, 10, 7], :dog=>[1, 2, 3, 4, 5, 6, 7]}, :name=>"mymouse"}, {:name=>"mymouse", :mouse=>{:cat=>[485, 11, 10], :dog=>[45, 54, 65]}}]
# Finds the value I want to update to 12
puts mynew.detect{|f| f[:name] == "mymouse"}[:mouse][:cat].detect{|x| x==485}
# results in an error
mynew.detect{|f| f[:name] == "mymouse"}[:mouse][:cat].detect{|x| x==485} = 12
# Does not update the value to 12
location = mynew.detect{|f| f[:name] == "mymouse"}[:mouse][:cat].detect{|x| x==485}
location = 12
puts mynew # Value unchanged
这是一种实现方法:
data = [
{
:name=>"mymouse",
:mouse=>{
:cat=>[485, 2, 10, 10, 10, 10, 7],
:dog=>[1, 2, 3, 4, 5, 6, 7]
},
},
{
:name=>"othermouse",
:mouse=>{
:cat=>[485, 11, 10],
:dog=>[45, 54, 65]
}
}
]
entry = data.find { |f| f[:name] == "mymouse" }
array = entry[:mouse][:cat]
modified_array = array.map { |n| n == 485 ? 12 : n }
entry[:mouse][:cat] = modified_array
require 'pp'
pp data
这将起作用;我测试了
另外,一旦有了数组,就可以使用:
array[array.index(485)] = 12
这将修改原始数组,因此其效果可能与我发布的未修改原始数组的主要解决方案不同。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句