gpt4 book ai didi

arrays - 如何遍历哈希和数组并替换字符串中的单词

转载 作者:数据小太阳 更新时间:2023-10-29 07:33:32 28 4
gpt4 key购买 nike

我正在尝试遍历字符串数组并替换符合任何替换规则的单词:

array= ["I love chicken!", "I love lamb!", "I love beef!"]
substitutions = {
"love" => "hate",
"lamb" => "turkey"
}

我想遍历数组并检查与替换哈希中的键匹配的任何单词。该数组将变为:

array= ["I hate chicken!", "I hate turkey!", "I hate beef!"]

这是我目前所拥有的:

array.each do |strings|
strings = strings.split
strings.each do |word|
substitutions.each do |phrase,substitute|
if word == phrase
word = substitute
return word
end
end
end
end

最佳答案

这将为您提供所需的结果。如您所见,您有点过于复杂了

arry= ["I love chicken!", "I love lamb!", "I love beef!"]
substitutions = { "love" => "hate", "lamb" => "turkey" }

arry.each_with_index do |str,ind|
substitutions.each_key do |word|
arry[ind].gsub!(word,substitutions[word]) if str.include?(word)
end
end

puts arry

这会给你:

[ "I hate chicken!", "I hate turkey!", "I hate beef!" ]

您拆分句子的策略行不通。感叹号会造成一些麻烦。在这种情况下,使用 #include? 进行测试的想法要好得多。

注意 gsub!(带有 !)的使用,这将对原始数组进行更改。

关于arrays - 如何遍历哈希和数组并替换字符串中的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41050733/

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