chief
chief

Reputation: 740

Locate a string in an array of strings

I would like to find the location in an array of all strings of any given word.

 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] 

Upvotes: 0

Views: 71

Answers (2)

megas
megas

Reputation: 21791

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]

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

Here's a way

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]

Upvotes: 2

Related Questions