0

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] 

2 Answers 2

2

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]
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. The regex is not needed since split removes the period on its own.
No, it doesn't.. And I'd be very surprised if it did.
t = phrase.scan(/[[:word:]]+/)
Hm, I thought, it could match whole words. For letters we have :alpha: :)
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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.