作者热门文章
- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我正在尝试遍历字符串数组并替换符合任何替换规则的单词:
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/
我是一名优秀的程序员,十分优秀!