Reputation: 11
I want to return the amount of vowels present in a given string argument. This is my code:
def count_vowels(string)
new = string.split("")
number_of_vowels = 0
new.each do |letters|
if letters = "a" || letters = "e" || letters = "i" || letters = "o" || letters = "u" ||
numbers_of_vowels = number_of_vowels + 1
end
end
number_of_vowels
end
For any argument, number_of_vowels
returns 0
. Any suggestions?
Upvotes: 0
Views: 213
Reputation: 106872
There are three issues in your code.
First, you have a typo in the variable number_of_vowels
within the loop. There you increment the counter to numbers_of_vowels
but never use that variable (with plural numbers
) again. Instead, you return number_of_vowels
(with singular number
) that still is 0
.
Second, =
in letters = "a"
assigns "a"
to the variable a
what would return truish all the time. Use ==
instead to compare if two values are equal.
Third, there is an orphan ||
at the end of the if
condition. What leads the following line be part of the condition. Because the first clause already returns truish the calculation is never evaluated.
This is how a fixed version might look like:
def count_vowels(string)
new = string.split("")
number_of_vowels = 0
new.each do |letters|
if letters == "a" || letters == "e" || letters == "i" || letters == "o" || letters == "u"
number_of_vowels = number_of_vowels + 1
end
end
number_of_vowels
end
Furthermore, you might want to simplify your code a bit:
# Appending an `i` to this regexp would enable case-insensitive
# matching and would find upper-case characters too.
VOWELS = /[aeiou]/
def count_vowels(string)
string.scan(VOWELS).size
end
Upvotes: 2
Reputation: 3692
You need to check for equality with ==
. =
just assigns.
Here -
if letters = "a" ||
should be if letters == "a" ||
.
Same for the rest.
Working code -
def count_vowels(string)
new = string.split("")
number_of_vowels = 0
new.each {|letters| number_of_vowels += 1 if letters == "a" || letters == "e" || letters =="i" || letters == "o" || letters == "u"}
number_of_vowels
end
Demo here.
Upvotes: 2