【问题标题】:What's the difference between "Hash.new(0)" and "{}"“Hash.new(0)”和“{}”有什么区别
【发布时间】:2017-06-12 04:41:19
【问题描述】:

我的代码中出现了(对我而言)意外的行为,因此我尝试在 REPL 中隔离问题。然而,这些构造函数似乎都有相同的结果(一个空哈希):

irb> a = {}
# => {}

irb> b = Hash.new(0)
# => {}

当我将{} 传递给reduce 函数时,我得到了NoMethodError。这两个构造函数有什么区别?

irb> arr = "count the occurance of each of the words".scan(/\w+/)
# => ["count", "the", "occurance", "of", "each", "of", "the", "words"]

irb> x = arr.reduce(Hash.new(0)) { |hsh, word| hsh[word] += 1; hsh }
# => {"count"=>1, "the"=>2, "occurance"=>1, "of"=>2, "each"=>1, "words"=>1}

irb> x = arr.reduce({}) { |hsh, word| hsh[word] += 1; hsh }
# NoMethodError: undefined method `+' for nil:NilClass

【问题讨论】:

  • Documentation 不清楚吗? “如果指定了 obj,则这个单一对象将用于所有默认值。”
  • 投反对票?这是一个合法的问题。我在 Ruby 上已经 3 天了(它是文档),不,我没有从文档中立即清楚地看到它。
  • 即使有例子?
  • 即便如此。实际上,早些时候我认为我错过了一些不言而喻的文档,但现在仔细观察,我看不到 {} 构造函数模式在哪里被描述或与 .new() 进行比较。那是哪里?

标签: ruby hash constructor


【解决方案1】:

Hash.new(0) 将任意键的默认值设置为0,而{} 设置nil

h1 = Hash.new(0)
h1.default  # => 0
h1[:a] += 1 # => 1
h2 = {}
h2.default  # => nil
h2[:a] += 1 # => NoMethodError: undefined method `+' for nil:NilClass

【讨论】:

  • 是构造函数的区别还是Hash.new(0)传递了一个零?或者换句话说,Hash.new(){} 是否等效?
  • @doub1ejack Hash.new() 相当于{}
【解决方案2】:

如果我们使用 Hash.new(0) 创建一个散列对象,在这种情况下,参数 0 将用作散列的默认值——如果您查找的键不是还在散列中

def count_frequency(word_list)
  counts = Hash.new(0)
  word_list.each { |word|
    counts[word] += 1
  }
   counts
end
p count_frequency(%w(red blue green red white black))

会产生

{"red"=>2, "blue"=>1, "green"=>1, "white"=>1, "black"=>1}

添加更多内容

brands= Hash.new( "nike" )
puts "#{brands[0]}"
puts "#{brands[101]}"

两者都会产生

nike
nike

brands = {0 => "nike" , 1 =>"Reebok"}
brands[0]   # => "nike"
brands[1]   # => "Reebok"
brands[100] # => nil

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2021-06-16
    • 2012-09-23
    • 2021-02-13
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多