0

我有汽车制造商的清单

 makes = [acura, honda, ford]

我正在尝试遍历一个字符串数组,并找出单个字符串是否包含其中一个品牌,如果包含,则将该特定品牌放入一个数组中

所以我有

strings.each do |string|

  if string.include?(*makes)

  else

  end
end

如何使用 splat 过程的当前参数来确定与字符串匹配的组成?有没有办法做到这一点?

编辑:正如我在下面的评论中发布的那样,我正在寻找要返回的特定品牌,而不是真/假答案。因此,如果字符串是“New toyota celica”,则返回应该是“toyota”。

4

3 回答 3

3

使用Enumerable#any?

makes = ['acura', 'honda', 'ford']
strings = ['hyundai acura ford', 'sports car']

strings.each do |string|
  p makes.any? { |make| string.include? make }
end

使用正则表达式的替代方法:(参见Regexp::union

strings = ['hyundai acura ford', 'sports car']
makes = ['acura', 'honda', 'ford']
pattern = Regexp.union(makes)

strings.each do |string|
  p string.match(pattern) != nil
end

更新

strings.each do |string|
  p makes.find { |make| string.include? make }
end

或者

strings.each do |string|
  p makes.select { |make| string.include? make }
end
于 2013-11-02T12:24:15.197 回答
1

如果你makes不是很长,那么最短的事情之一就是使用正则表达式,正如已经建议的那样:

makes = ['acura', 'honda', 'ford']
strings = ['hyundai acura ford', 'sports car']
strings.grep(/#{makes.join('|')}/)

 # => ["hyundai acura ford"]

经过轻微讨论,我们认为这是最佳选择之一:

strings.grep(Regexp.union(makes))
于 2013-11-02T12:37:30.130 回答
0

另一种方式,通过相交数组:

makes = ["acura", "honda", "ford"]

strings = [
"I own a Toyota and a Ford",
"My friend Becky loves her Acura",
"I plan to buy a BMW",
"I now have an Acura, but have had both a honda and a Ford"
]

strings.each do |s|
  a = s.scan(/(\w+)/).flatten.map(&:downcase) & makes
  puts "#{s}\n" + (a.empty? ? "  No matches" : "  Matches: #{a.join}")
end

I own a Toyota and a Ford
  Matches: ford
My friend Becky loves her Acura
  Matches: acura
I plan to buy a BMW
  No matches
I now have an Acura, but have had both a honda and a Ford
  Matches: acura honda ford

请注意,必须使用scan正则表达式,而不是split,因为后者会出现标点符号问题(例如,'Acura' 将不匹配)。

于 2013-11-03T00:07:54.410 回答