【问题标题】:adding a hash to hash or symbol on the fly Ruby动态添加哈希到哈希或符号 Ruby
【发布时间】:2014-02-22 11:01:04
【问题描述】:

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

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

【问题讨论】:

    标签: ruby arrays hash symbols


    【解决方案1】:
    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
    

    【讨论】:

      【解决方案2】:

      只要找到键,Hash 的 default_proc 就会运行。在这里,它创建了一个新的哈希值作为新键的值:

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-08
        • 2014-04-28
        • 2011-05-27
        相关资源
        最近更新 更多