2012-06-01 139 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]