9

我有一段这样的代码:

my_hash = {}
first_key = 1
second_key = 2
third_key = 3
my_hash[first_key][second_key][third_key] = 100

红宝石解释器给了我一个错误说:

nil:NilClass (NoMethodError) 的未定义方法“[]”

那么这是否意味着我不能像那样使用哈希?还是您认为此错误可能是由于其他原因?

4

4 回答 4

12

默认情况下,哈希不嵌套。由于my_hash[first_key]未设置任何内容,因此是nil. 并且nil不是哈希,因此尝试访问其中一个元素会失败。

所以:

my_hash = {}
first_key = 1
second_key = 2
third_key = 3

my_hash[first_key] # nil
my_hash[first_key][second_key]
# undefined method `[]' for nil:NilClass (NoMethodError)

my_hash[first_key] = {}
my_hash[first_key][second_key] # nil

my_hash[first_key][second_key] = {}

my_hash[first_key][second_key][third_key] = 100
my_hash[first_key][second_key][third_key] # 100
于 2012-05-01T01:46:10.497 回答
8

您使用散列的方式在 Ruby 中无效,因为必须先将每个值分配给一个散列,然后才能使用嵌套散列(我想您来自 PHP?),但您可以使用 vivified 散列:

my_hash = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc)}
first_key = 1
second_key = 2
third_key = 3
my_hash[first_key][second_key][third_key] = 100
p my_hash

#output: {1=>{2=>{3=>100}}}

这是您可能会感到舒服的方式。

于 2012-05-01T03:21:33.457 回答
2

你不能使用这样的哈希值;my_hash[first_key]只是零,然后下一个索引操作失败。可以创建一个哈希对象,其行为方式与您正在寻找的方式相同——参见http://taw.blogspot.co.uk/2006/07/autovivification-in-ruby.html——但目前尚不清楚这是很好的风格。

于 2012-05-01T01:47:02.787 回答
0

你可以做类似的事情

class NilClass

  def [] key
    nil
  end

end

在初始化程序中nil_overrides.rb,您将能够使用nil['xxx'].

于 2014-05-19T00:05:00.557 回答