我想写一个函数来计算str中所有字母的出现次数,听起来很简单,我想出了这个
def letter_count(str)
hash = {}
letters = str.gsub(' ','').split('')
letters.each do |letter|
if hash.include?(letter)
hash[letter] += 1
else
hash[letter] = 1
end
end
hash
end
letter_count('moon') => {"m"=>1, "o"=>2, "n"=>1}
当我试图将其缩短为
def letter_count(str)
hash = {}
letters = str.gsub(' ','').split('')
letters.each do |letter|
hash[letter] += 1 if hash.include?(letter)
hash[letter] = 1
end
hash
end
答案变成了:
letter_count('moon') => {"m"=>1, "o"=>1, "n"=>1}
你能告诉我我哪里出错了吗???谢谢!!!!!!!