Bovinewill74
Bovinewill74

Reputation: 33

Scanning an array of strings for matches in Ruby

I have an array of string and I want to search for a certain words (cat or dog) in each string within the array and be able to view the results in the order they came.

Example sentences

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 ever get the last match in the results. how might I do this correctly to get puts $1 => cat puts $2 => dog? Thank you for your assistance

Upvotes: 3

Views: 8694

Answers (4)

tokland
tokland

Reputation: 67850

sentences = [
  "Subject family leans toward cats",
  "Test subject prefers dogs",
]

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

Upvotes: 2

fl00r
fl00r

Reputation: 83680

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

so now you can puts it:

puts cats_and_dogs[0]
#=> "cat"
puts cats_and_dogs[1]
#=> "dog"
puts cats_and_dogs.join(" & ")
#=> "cat & dog"

Upvotes: 4

Mark
Mark

Reputation: 17132

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

Upvotes: 0

DigitalRoss
DigitalRoss

Reputation: 146043

I don't entirely understand the question but try this and see if it helps you make progress:

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

Upvotes: 0

Related Questions