我有串這樣從Ruby中的字符串獲取數組中任何字符的第一個索引?
hi, i am not coming today!
和我有人物像這樣的數組:
['a','e','i','o','u']
現在我想找到任何單詞的從字符串數組中第一次出現。
如果它只有一句話我會已經能夠做到這一點是這樣的:
'string'.index 'c'
我有串這樣從Ruby中的字符串獲取數組中任何字符的第一個索引?
hi, i am not coming today!
和我有人物像這樣的數組:
['a','e','i','o','u']
現在我想找到任何單詞的從字符串數組中第一次出現。
如果它只有一句話我會已經能夠做到這一點是這樣的:
'string'.index 'c'
s = 'hi, i am not coming today!'
['a','e','i','o','u'].map { |c| [c, s.index(c)] }.to_h
#⇒ {
# "a" => 6,
# "e" => nil,
# "i" => 1,
# "o" => 10,
# "u" => nil
# }
要找到任何字符的從一個數組中第一次出現:
['a','e','i','o','u'].map { |c| s.index(c) }.compact.min
#⇒ 1
UPD不同之處:
idx = str.split('').each_with_index do |c, i|
break i if ['a','e','i','o','u'].include? c
end
idx.is_a?(Numeric) ? idx : nil
str =~ /#{['a','e','i','o','u'].join('|')}/
str.index Regexp.union(['a','e','i','o','u']) # credits @steenslag
你期望它能夠與你給出的例子一起返回嗎? – mtamhankar
1因爲「i」在數組中,並且字符串 –
中的第一項可以爲您的示例提供期望的輸出嗎? – xlembouras