質問

I have a list of car makes

 makes = [acura, honda, ford]

and I'm trying to iterate through an array of strings and find out if the individual string contains one of these makes AND if it does, to put that specific makes into an array

so I've got

strings.each do |string|

  if string.include?(*makes)

  else

  end
end

how do I use the current argument of the splat process to determine which make matched up with the string? Is there a way to do this?

Edit: As I posted in the comments below, I'm looking for a specific make to be returned, instead of a true/false answer. So if the string is "New toyota celica", the return should be "toyota".

役に立ちましたか?

解決

Using Enumerable#any?:

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

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

Alternative that use regular expression: (See 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

UPDATE

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

or

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

他のヒント

If Your makes are not very long, then one of the shortest thing would be using Regex, as already suggested:

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

 # => ["hyundai acura ford"]

After a slight discussion we came up this to be one of the best choices:

strings.grep(Regexp.union(makes))

Another way, by intersecting arrays:

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

Note that it is necessary to use scan with a regex, rather than split, as punctuation would be a problem with the latter (e.g., 'Acura,` would not be matched).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top