2015-08-21 59 views
0

我有串這樣從Ruby中的字符串獲取數組中任何字符的第一個索引?

hi, i am not coming today! 

和我有人物像這樣的數組:

['a','e','i','o','u'] 

現在我想找到任何單詞的從字符串數組中第一次出現。

如果它只有一句話我會已經能夠做到這一點是這樣的:

'string'.index 'c' 
+0

你期望它能夠與你給出的例子一起返回嗎? – mtamhankar

+0

1因爲「i」在數組中,並且字符串 –

+0

中的第一項可以爲您的示例提供期望的輸出嗎? – xlembouras

回答

2
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 
+0

我想對於一個字符可能是從字符串 –

+1

任何字符,你可以舉個例子,爲什麼這個答案是不正確的? – BookOfGreg

+0

第二版是正確的,我只是在等着看有人想出了不同的東西。 –

相關問題