我想知道如何动态添加哈希值 并增加内部的哈希值。
words_to_scan.scan(/\w+|\?|\.|!|\,/).select do |aword|
if words_from_file.has_key?(aword.to_sym)
words_from_file[aword.to_sym]['pop'] += 1
else
words_from_file[aword.to_sym]['pop'] = 1
end
end
我正在尝试创建像
这样的东西words_from_file = {:the => {'pop' => 3, 'positions' => [1,6,10]}}
答案 0 :(得分:0)
words_from_file = {}
words_to_scan.scan(/\w+|\?|\.|!|\,/).select do |aword|
words_from_file[aword.to_sym] ||= {} # declare hash if was not already declared
words_from_file[aword.to_sym]['pop'] ||= 0 # set pop if was not already set
words_from_file[aword.to_sym]['pop'] += 1 # increment
end
答案 1 :(得分:0)
只要找不到 的密钥,就会运行Hash的default_proc。在这里,它为新键创建一个新的Hash值:
words_from_file.default_proc = Proc.new{|h,k,v| h[k] = {'pop' => 0, 'positions' => []} }
words_to_scan.scan(/\w+|\?|\.|!|\,/).each do |aword|
words_from_file[aword.to_sym]['pop'] += 1
end