我想在任何给定单词的所有字符串的数组中找到位置。
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
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."
phrase.split(/[\W]+/).each_with_index.each_with_object([]) do |obj,res|
res << obj.last if obj.first == "happy"
end
#=> [2, 6]