Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count vowels in a string with ruby

Tags:

iteration

ruby

My objective is to return the number of vowels in a given string. I've tried this code:

def count_vowels(string)
  vowels = ['a', 'e', 'i', 'o', 'u']
  chars_ary = string.split(//)
  ary_with_vowels = chars_ary.take_while {|letter| vowels.include?(letter)}
  return ary_with_vowels.length
end

and it doesn't pass the majority of test cases. I understand that there are multiple other ways to solve this problem, but I want to solve it using the code that I provided.

Can someone give me some insight as to why this isn't working?

like image 703
Justin Hernandez Avatar asked May 05 '26 20:05

Justin Hernandez


1 Answers

This way is easier:

 def count_vowels(string)
   string.count('aeiou')
 end
like image 99
user1934428 Avatar answered May 07 '26 09:05

user1934428



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!