我有一个复杂的数据结构(多个哈希数组)。我想找到并更新一个特定的值。但是,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发布于 2014-10-22 22:18:08
有一种方法可以做到:
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这将修改原始数组,因此它可能会产生与我发布的主要解决方案不同的效果,该解决方案不修改原始数组。
https://stackoverflow.com/questions/26517934
复制相似问题