Reputation: 18159
I have string like this
hi, i am not coming today!
and i have an array of characters like this:
['a','e','i','o','u']
now i want to find the first occurrence of any word from array in string.
If it was only word i'd have been able to do it like this:
'string'.index 'c'
Upvotes: 0
Views: 136
Reputation: 121010
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
# }
To find the first occurence of any character from an array:
['a','e','i','o','u'].map { |c| s.index(c) }.compact.min
#⇒ 1
UPD Something different:
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
Upvotes: 2