Arrays 如何迭代散列和数组并替换字符串中的单词

Arrays 如何迭代散列和数组并替换字符串中的单词,arrays,ruby,hash,iterator,Arrays,Ruby,Hash,Iterator,我试图遍历一个字符串数组,如果它们符合任何替换规则,则替换它们: array= ["I love chicken!", "I love lamb!", "I love beef!"] substitutions = { "love" => "hate", "lamb" => "turkey" } 我希望遍历数组,并检查是否有任何单词与替换哈希中的键匹配。然后,阵列将变为: array= ["I hate chicken!", "I hate turkey!", "I hate be

我试图遍历一个字符串数组,如果它们符合任何替换规则,则替换它们:

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的用法(使用!),将对原始数组进行更改。

arr=[“我爱鸡肉!”、“我爱羔羊!”、“我爱牛肉!”]
arr  = ["I love chicken!", "I love lamb!", "I love beef!"]
subs = { "love"=>"hate", "lamb"=>"turkey" }

subs.default_proc = ->(h,k) { k }
  #=> #<Proc:0x007f9ff0a014b8@(irb):1343 (lambda)>
arr.map { |s| s.gsub(/\w+/, subs) }
  #=> ["I hate chicken!", "I hate turkey!", "I hate beef!"]
subs={“爱”=>“恨”,“羔羊”=>“土耳其”} subs.default_proc=->(h,k){k} #=> # arr.map{| s | s.gsub(/\w+/,subs)} #=>[“我讨厌鸡肉!”,“我讨厌火鸡!”,“我讨厌牛肉!”]

我过去常常在
subs
上附加一个proc,这样
subs[k]
如果
subs
没有键
k
,就返回
k
,并使用使用散列进行替换的形式。

根本不需要对散列进行迭代。而是使用它生成正则表达式并将其传递给
gsub
。以下是我做过很多次的事情;它是模板引擎的基础:

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

key_regex = /\b(?:#{Regexp.union(substitutions.keys).source})\b/
# => /\b(?:love|lamb)\b/

array.map! { |s|
  s.gsub(key_regex, substitutions)
}

array # => ["I hate chicken!", "I hate turkey!", "I hate beef!"]
如果不想咀嚼
array
的内容,请改用
map
,它将返回一个新数组,而原始数组保持不变:

array.map { |s|
  s.gsub(key_regex, substitutions)
}
# => ["I hate chicken!", "I hate turkey!", "I hate beef!"]

array # => ["I love chicken!", "I love lamb!", "I love beef!"]
诀窍是定义用于查找关键字的正则表达式


有关更多信息,请参见“”和文档。

无需定义键数组
单词
。使用