gpt4 book ai didi

Ruby 使用检测更新值

转载 作者:太空宇宙 更新时间:2023-11-03 16:25:00 24 4
gpt4 key购买 nike

我有一个复杂的数据结构(多级哈希数组)。我想查找并更新特定值。但是,detect 似乎没有传递对我要更新的数据结构中位置的引用。我可以使用 eacheach_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

这会修改原始数组,因此它可能会产生与我发布的主要解决方案不同的效果,后者不会修改原始数组。

关于Ruby 使用检测更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517934/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com