在下面的代码从1
"seven"
变化2
值:Ruby - 为什么+ =会增加我的字符串的数量?
word_counts = Hash.new(0)
sample = "If seven maids with seven mops"
sample.split.each do |word|
word_counts[word.downcase] += 1
puts word_counts
end
输出:
{}
{"if"=>1}
{"if"=>1, "seven"=>1}
{"if"=>1, "seven"=>1, "maids"=>1}
{"if"=>1, "seven"=>1, "maids"=>1, "with"=>1}
{"if"=>1, "seven"=>2, "maids"=>1, "with"=>1}
{"if"=>1, "seven"=>2, "maids"=>1, "with"=>1, "mops"=>1}
有人可以解释为什么它从1
去2
?
你知道'+ ='操作符的作用吗? – Ryan
试着用“样品=”七七七七“'。注意什么? –
好吧,我超级愚蠢,我想我没有读过字符串中有两个“sevens”。我只是看了其余的代码,假设初始字符串都是唯一的。谢谢你们 –