【发布时间】:2018-02-05 03:53:57
【问题描述】:
在以下代码中,"seven" 的值从 1 更改为 2:
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?
【问题讨论】:
-
你知道
+=运算符是做什么的吗? -
试试
sample = "seven seven seven seven seven"。注意到什么了吗? -
好吧,我超级愚蠢,我想我没有读到字符串中有两个“七”。假设初始字符串都是唯一的,我只是查看了其余代码。谢谢大家
标签: ruby string dictionary hash counter