2015-08-21 60 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

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

相关问题