【发布时间】:2014-06-19 19:08:24
【问题描述】:
在尝试查找“fantastic”中字母的频率时,我无法理解给定的解决方案:
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}
谁能分解代码片段并告诉我潜在的区别是什么。我想一旦我理解了这一点,我将能够真正理解第一段代码。此外,如果您想解释一下第一段代码以帮助我,那也很棒。
【问题讨论】: