Home > Mobile >  In given array of strings, grab only vowel containing words
In given array of strings, grab only vowel containing words

Time:09-02

I am new in ruby and learning basics, i am stuck on this for quite sometime.

Tried doing :

Str="Hi there buddy, long time no see."

arr=str.split()

vow=["a","e","i","o","u"]

arr.select {|x| x.include? vow}

I don't even know what is wrong in this, and why it isn't working..

CodePudding user response:

The grep method is good for this:

arr = ["first", "second", "nth"]
arr.grep(/[aeiou]/)
# => ["first", "second"]

It returns all of the array elements that match the given regular expression; the regular expression /[aeiou]/ matches any string that contains a vowel.

CodePudding user response:

You're close, but you need to determine for each word, if any of the vowels are present in that word.

arr.select { |word| 
  word.filter { |ch| vow.include? ch } 
}

But you only need to if the word contains any vowels, but all of the vowels it contains. Now word is a String, and doesn't work with #any?, but Array does, so we flip it around to check if the word contains any vowel.

arr.select { |word| 
  vow.any? { |v| word.include? v } 
}

You could also use regular expressions to accomplish this:

arr.filter { |w| w =~ /\w*[aeiou]\w*/ }

Or with the vowels not hard-coded:

arr.filter { |w| w =~ /\w*[#{vow.join}]\w*/ }
  •  Tags:  
  • ruby
  • Related