Ruby 在字符串数组中查找字符串

Ruby 在字符串数组中查找字符串,ruby,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] 有个办法 phrase =

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

 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] 
有个办法

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]
有个办法

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]
phrase=“我很高兴看到你快乐。”
短语.split(/[\W]+/)。每个_带有_索引。每个_带有_对象([])do | obj,res|
决议[2,6]
短语=“我很高兴看到你快乐。”
短语.split(/[\W]+/)。每个_带有_索引。每个_带有_对象([])do | obj,res|
决议[2,6]

谢谢你的回答。不需要正则表达式,因为split会自行删除句点。。如果有,我会非常惊讶。
t=phrase.scan(/[:word:]+/)
Hm,我想,它可以匹配整个单词。我们收到的信件:阿尔法::)谢谢你的回答。不需要正则表达式,因为split会自行删除句点。。如果有,我会非常惊讶。
t=phrase.scan(/[:word:]+/)
Hm,我想,它可以匹配整个单词。对于字母,我们有:alpha::)