"two", :key3=>"three"}, {:key1=>"four", :key2=>"-6ren">
gpt4 book ai didi

ruby - 如何替换散列中包含的值?

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

我有一个哈希数组:

arr = [
{:key1=>"foo one bar", :key2=>"two", :key3=>"three"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

如果 :key 包含“one”,我想搜索并用 "replaced" 替换 :key1 的值。

结果数组将显示为:

arr = [
{:key1=>"replaced", ;key2=>"two", :key3=>"three"},
{:key1=>"four", ;key2=>"five", :key3=>"six"},
{:key1=>"seven", ;key2=>"eight", :key3=>"nine"}
]

我尝试使用我之前帖子中的 include? 并在“Replace one matched value in a hash with another”中回复,但无济于事。

这些将得到完全匹配:

arr.each{|item| item[:key1] = "replaced" if item[:key1]=="one"}

随心所欲:

p arr.each {|x| x[:key1] = "replaced" if x.values_at(:key1) == "one"}

但我需要它只包含字符串术语。

最佳答案

arr = [
{:key1=>"foo one bar", :key2=>"two", :key3=>"three"},
{:key1=>"four", :key2=>"five", :key3=>"six"},
{:key1=>"seven", :key2=>"eight", :key3=>"nine"}
]

arr.each {|x| x[:key1] = 'replaced' if x[:key1].include? 'one'}
p arr

输出:

[{:key1=>"replaced", :key2=>"two", :key3=>"three"}, {:key1=>"four", :key2=>"five", :key3=>"six"}, {:key1=>"seven", :key2=>"eight", :key3=>"nine"}]

关于ruby - 如何替换散列中包含的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16122384/

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