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] 
4

2 に答える 2

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]
于 2012-06-01T21:13:05.890 に答える
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]
于 2012-06-01T21:20:00.337 に答える