我有串这样从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