在Ruby上添加哈希到哈希或符号

时间:2014-01-30 08:41:37

标签: ruby arrays hash symbols

我想知道如何动态添加哈希值 并增加内部的哈希值。

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]}}

2 个答案:

答案 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