在Ruby中扫描匹配的字符串数组

时间:2011-03-09 20:40:55

标签: ruby arrays string

我有一个字符串数组,我想在数组中的每个字符串中搜索某些单词(cat或dog),并能够按照它们的顺序查看结果。

例句

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

我尝试了String.each {|x| x.scan(/cat|dog)/ },但我只会在结果中获得最后一场比赛。我怎样才能正确地获得puts $1 => cat puts $2 => dog?感谢您的帮助

4 个答案:

答案 0 :(得分:4)

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

所以现在你可以puts

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

答案 1 :(得分:2)

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

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

答案 2 :(得分:0)

我不完全理解这个问题,但试试这个,看看它是否有助于你取得进步:

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

答案 3 :(得分:0)

这应该适合你。

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

输出:

cat
dog
cat