javascript - Ruby - 数组检查并替换为

标签 javascript ruby arrays loops replace

给定:

check_for = ["Lorem", "ipsum", "dolor", "sit", "amet"]

replace_with = ["Donec", "ut", "libero", "sed", "arcu"]

sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec a diam lectus. Sed sit amet ipsum mauris. Maecenas congue ligula ac quam viverra nec consectetur ante hendrerit. Donec et mollis dolor. Praesent et diam eget libero egestas mattis sit amet vitae augue. Nam tincidunt congue enim, ut porta lorem lacinia consectetur."

如果 'sentence' 中包含数组 'check_for' 中的单词,我如何检查整个字符串,如果找到它们,则替换为 'replace_with' 中的单词?

check_for 中的词可以用 replace_with 中具有相同索引的词替换:

check_for[idx] 应替换为 replace_with[idx]

我使用嵌套循环对 Javascript 做了一些“类似”的事情。由于某些原因,这不适用于 Ruby。

我对嵌套循环的想法是将句子拆分成数组,并使用带有 i 和 j 的 while 循环。所以 sentence[i] 将从 0 开始:

sentence[i] == check_for[j]

然后:

sentence[i] = replace_with[j]

除了这个想法行不通之外,我确信在 Ruby 中还有更直接的方法。

不区分大小写是可以的。

最佳答案

这可以通过定义替换的散列来完成:

sentence = "Lorem ipsum dolor sit amet, consectetur adipiscing elit..."
replacements = {
  'Lorem' => 'Donec',
  'ipsum' => 'ut',
  'dolor' => 'libero',
  'sit'   => 'sed',
  'amet'  => 'arcu',
}

sentence.gsub(Regexp.union(replacements.keys), replacements)
#=> "Donec ut libero sed arcu, consectetur adipiscing elit..."

顺便说一句,您可以像这样从数组中轻松生成 replacements 哈希:

replacements = Hash[check_for.zip(replace_with)]

Cary Swoveland 建议使用简化的正则表达式:

sentence.gsub(/\w+/, replacements)

我真的很喜欢,因为它读起来更漂亮。

我想知道 rexexp 是否对性能有影响:一方面构建复杂但专门的 regexp。另一方面,使用简单的正则表达式,但必须根据哈希检查每个单词。

require 'benchmark'

def simple
  @sentence.gsub(/\w+/, @replacements)
end

def union
  @sentence.gsub(Regexp.union(@replacements.keys), @replacements)
end

n = 100_000
Benchmark.bmbm(15) do |x|
  x.report("simple :")   { n.times do; simple; end }
  x.report("union  :")   { n.times do; union ; end }
end

# Rehearsal ---------------------------------------------------
# simple :          4.790000   0.010000   4.800000 (  4.804576)
# union  :          3.820000   0.020000   3.840000 (  3.846012)
# ------------------------------------------ total: 8.640000sec

事实证明,较长的版本速度更快一些。但我很确定这可能会根据 sentence 的长度和要替换的元素数量而改变。

关于javascript - Ruby - 数组检查并替换为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28736704/

相关文章:

ruby - 使用 Ruby 将字符串转换为日期

c# - 检查是否已使用数组的所有值

javascript - 如果数组包含 Javascript 中的字符串,如何检查它?

javascript - svg图像缩放、平移和编辑

javascript - 如果在 javascript-meteor 中不起作用

ruby - 为什么 << 方法显式返回自助方法链接?

java - Java可以使用String作为索引数组键吗? (例如 : array ["a"]=1;)

javascript - Node js : percentage based string compare

javascript - 使用 AsyncStorage 更新状态 - React Native

ruby-on-rails - rails : How to get url like/users/2/events/2009-02. html