Scan an array of strings for matches in Ruby

I have an array of strings, and I want to search for specific words (cat or dog) in each row of the array and be able to view the results in the order in which they were.

Examples of offers

Strings[0] = "Subject family leans toward cats" 
Strings[1] = "Test subject prefers dogs"

I tried String.each {|x| x.scan(/cat|dog)/ }, but I would only get the last result in the results. how can i do it right to get puts $1 => cat puts $2 => dog? Thank you for your help.

+3
source share
4 answers
strings = [ "Subject family leans toward cats",
            "Test subject prefers dogs" ]
cat_and_dogs = strings.join.scan /cat|dog/
#=> ["cat", "dog"]

now you can putsit:

puts cats_and_dogs[0]
#=> "cat"
puts cats_and_dogs[1]
#=> "dog"
puts cats_and_dogs.join(" & ")
#=> "cat & dog"
+4
source
sentences = [
  "Subject family leans toward cats",
  "Test subject prefers dogs",
]

sentences.flat_map { |s| s.scan(/dog|cat/) }
# => ["cat", "dog"]   
+2
source

I don’t quite understand the question, but I’ll try it and see if it helps you make progress:

["...", "..."].map { |e| e[/cat|dog/] }
0
source

This should work for you.

list = ["Subject family leans toward cats.","Tes subject perfers dogs not cats"]
list.each { |x| 
    puts x.scan(/cat|dog/) 
}

output:

cat
dog
cat
0
source

All Articles