当试图找到在“梦幻般的”我无法理解给定的解决方案字母频率:频率在字符串中的字母
def letter_count(str)
counts = {}
str.each_char do |char|
next if char == " "
counts[char] = 0 unless counts.include?(char)
counts[char] += 1
end
counts
end
我试图解构它,当我创建了下面的一段代码我希望它做同样的事情。但它给了我不同的结果。
blah = {}
x = 'fantastic'
x.each_char do |char|
next if char == " "
blah[char] = 0
unless
blah.include?(char)
blah[char] += 1
end
blah
end
的第一段代码给我下面的
puts letter_count('fantastic')
>
{"f"=>1, "a"=>2, "n"=>1, "t"=>2, "s"=>1, "i"=>1, "c"=>1}
为什么代码的第二件让我
puts blah
>
{"f"=>0, "a"=>0, "n"=>0, "t"=>0, "s"=>0, "i"=>0, "c"=>0}
有人能打破的代码片段,并告诉我根本的区别是什么。我想,一旦我明白了这一点,我就能够真正理解第一段代码。另外如果你想解释一下关于帮助我的第一段代码,那也会很棒。