David Charles
David Charles

Reputation: 21

What's wrong with this Ruby program that counts vowels?

When I test this program on strings the output is 0. I think my logic is sound and it's just a minor syntax thing. Anyone see the problem?

def VowelCount(string)

  string.downcase
  i = 0
  vowels = 0

  until i == string.length-1
    if (string[i] == "a" || string[i] == "o" || string[i] == "e" || string[i] == "i" || string[i] == "u")
      vowels += 1
      end
    i += 1
    end
  return vowels
  end

Upvotes: 1

Views: 609

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110685

You can use String#count:

str = "It was the best of times, it was the worst of times,..."

str.downcase.count('aeiou') #=> 14

Upvotes: 5

falsetru
falsetru

Reputation: 369144

The following line

until i == string.length-1

should be:

until i == string.length

Otherwise, the last character is not checked.

BTW, by convension, method name starts with lower case, and combined with underscore. Here's an alternative solution using regular expression.

def vowel_count(string)
  string.scan(/[aeiou]/i).length
end

update

As JesseSielaff pointed, String#downcase does not change the string in place. You need to assign the return value of the method back or use String.downcase!

Upvotes: 3

Related Questions