2012-06-01 103 views
0

我想查找任何给定字的所有字符串数组中的位置。查找字符串数组中的字符串

phrase = "I am happy to see you happy." 
t = phrase.split 
location = t.index("happy") # => 2 (returns only first happy) 




    t.map { |x| x.index("happy") } # => returns [nil, nil, 0, nil, nil, nil, 0] 

回答

2

这里是一种

phrase = "I am happy to see you happy." 
t = phrase.split(/[\s\.]/) # split on dot as well, so that we get "happy", not "happy." 

happies = t.map.with_index{|s, i| i if s == 'happy'} # => [nil, nil, 2, nil, nil, nil, 6] 
happies.compact # => [2, 6] 
+0

感谢您的回答。正则表达式是不需要的,因为split会自行删除句点。 – chief

+2

[不,它不。](http://pastie.org/4010321)。如果确实如此,我会很惊讶。 –

+0

好吧,我站好了! – chief

1
phrase = "I am happy to see you happy."  
phrase.split(/[\W]+/).each_with_index.each_with_object([]) do |obj,res| 
    res << obj.last if obj.first == "happy" 
end 
#=> [2, 6]