arrays - map function that returns numerical 0 or 1 for true or false -


i'm trying count number of vowels in string splitting string array of letters , map vowel letters 1 , summing array.

def count_vowels(string)     vowels = ['a','e', 'i', 'o', 'u']     return string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+) end 

the include? part doesn't correctly return 1 or 0. suggestion why won't fly?

i hacked version works, looks kind of foolish:

def count_vowels(string)     vowels = ['a','e', 'i', 'o', 'u']     return string.split("").map{ |n| vowels.include? n}.inject(0) |mem,x|         x ? mem + 1 : mem     end end 

the reason:

string.split("").map{ |n| vowels.include? n ? 1 : 0}.inject(0,:+) 

does not work because n ? 1 : 0 evaluated , passed argument include? instead of n. need add parentheses in include?:

string.split("").map{ |n| vowels.include?(n) ? 1 : 0}.inject(0,:+) 

you can do

def count_vowels(string)   vowels = ['a','e', 'i', 'o', 'u']   string.split(//).select { |x| vowels.include? x }.length end 

Comments