0

For all vowels in a string, I'm trying to print the amount of the vowels. If I push every instance of a vowel to a new array, then the length of the array + 1 would be the answer. I don't know if my push is failing. Any help would be appreciated.

def count_vowels(string)
  arr = ['a', 'e', 'i', 'o', 'u']
  letters = string.split("")
  letters.each do |x|
    if x == arr.any?
      vowels = vowels.push(x) 
      print vowels.length
    else
      print 0
    end
end

2 Answers 2

3

Once you get more familiar with Ruby, you'll realize there are much more useful methods than "each" for things you're trying to accomplish, like counting the vowels in a string. Like for example:

my_string = 'Hey there'

def how_many_vowels_has(this_string)
  this_string.scan(/[aeiou]/).size
end

p how_many_vowels_has(my_string) #=> 3

or you can call String#count on the string itself:

my_string = 'Hey there'
p my_string.count('aeiou') #=> 3

From what I can see, you need to spend more time learning about how Enumerable works, scope and the fact that everything in Ruby is an object. Also, solving problems the "Ruby" way, using the constructs the language provides you.

Sign up to request clarification or add additional context in comments.

5 Comments

Speaking of methods more useful for counting vowels in a string, this is what we have String#count for: this_string.count('aeiou') #=> 3
Edited my answer to add this as well, thanks @Jordan
Actually, that should be either this_string.downcase.count('aeiou') or this_string.count('AaEeIiOoUu'). My bad.
thank you. i am going through some intro tutorials but the practice problems ask you to solve them using the information provided. this becomes challenging because your code is obviously more concise and works but the idea is to learn how to think like the computer. either way it gets a little frustrating. thank you for your help.
@GeraldAnekwe That makes sense, but it's hard for us to give you suggestions that only use the information you have so far, because we don't know what information you have so far.
1

The problem is with arr.any? it does not do what you think it does.

According to the documentations:

Passes each element of the collection to the given block. The method returns true if the block ever returns a value other than false or nil

Instead, you want to use if arr.include? x

1 Comment

if you find this answer helpful, please consider accepting it, or accepting @daremkd 's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.