0

I'm making a method in Ruby to count how many vowels are in a string. I figured it out, but at first I made the mistake of not repeating "variable==" after every '||'. The correct way seems inefficient. Is there a quicker way to do this and get the same result?

See example:

CORRECT:

def count_vowels(string)

vnum = 0 
n = 0

while n < string.length 
    if string[n] == "a"||string[n] == "e"||string[n] =="i"||string[n]  =="o"||string[n] =="u"||string[n] =="y"
        vnum += 1 
    end 
    n += 1 
end 

return vnum 

end

INCORRECT:

def count_vowels(string)

vnum = 0 
n = 0

while n < string.length 
    if string[n] == "a"|| "e"||"i"||"o"||"u"||"y"
        vnum += 1 
    end 
    n += 1 
end 

return vnum 

end
David Makogon
  • 69,407
  • 21
  • 141
  • 189
Steven Anderson
  • 455
  • 6
  • 13
  • You can use include like https://ruby-doc.org/core-2.2.0/Array.html#method-i-include-3F – inye Nov 04 '16 at 02:55
  • You might want to pick up a good reference on regular expressions because `string.scan(/[aeiou]/).length` is the quickest way to do this. – tadman Nov 04 '16 at 03:26

0 Answers0