在字符串数组中找到一个字符串

时间:2012-06-01 21:05:47

标签: ruby

我想在任何给定单词的所有字符串的数组中找到该位置。

 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 个答案:

答案 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]

答案 1 :(得分: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]