Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 类变量正在被重写_Ruby_Ruby 1.9.2 - Fatal编程技术网

Ruby 类变量正在被重写

Ruby 类变量正在被重写,ruby,ruby-1.9.2,Ruby,Ruby 1.9.2,我在使用哈希作为类变量时遇到了一个奇怪的问题。运行以下代码后,我希望类变量@@class_hash应该包含{:one=>{'a'=>'one'},:two=>{'a'=>'two'} 但是,在我运行此代码之后,@@class_hash是{:one=>{'a'=>'two'},:two=>{'a'=>'two'} 为什么呢 class Klass @@class_hash = Hash.new({}) def fun1 @@class_hash[:one]['a'] = 'one

我在使用哈希作为类变量时遇到了一个奇怪的问题。运行以下代码后,我希望类变量
@@class_hash
应该包含
{:one=>{'a'=>'one'},:two=>{'a'=>'two'}

但是,在我运行此代码之后,
@@class_hash
{:one=>{'a'=>'two'},:two=>{'a'=>'two'}

为什么呢

class Klass
  @@class_hash = Hash.new({})

  def fun1
    @@class_hash[:one]['a'] = 'one'
  end

  def fun2
    @@class_hash[:two]['a'] = 'two'
  end

  def class_hash
    @@class_hash
  end
end

klass = Klass.new

klass.fun1
h1 = klass.class_hash
raise "h2[:one]['a'] should be 'one', not 'two'" if h1[:one]['a'] == 'two'
klass.fun2
h2 = klass.class_hash
raise "h2[:one]['a'] should be 'one', not 'two'" if h2[:one]['a'] == 'two'

Hash.new的参数用作默认值,在您的案例{}中

对未知密钥的每次访问都使用完全相同的对象(ruby不会神奇地为您复制它),因此在您的情况下,每个密钥的值都是完全相同的散列。你可以完成我认为你想要的块形式

Hash.new {|hash, key| hash[key] ={} }

在本例中,将为每个缺少的键使用不同的空哈希。

hash.new的参数用作默认值,在本例中为{}

对未知密钥的每次访问都使用完全相同的对象(ruby不会神奇地为您复制它),因此在您的情况下,每个密钥的值都是完全相同的散列。你可以完成我认为你想要的块形式

Hash.new {|hash, key| hash[key] ={} }
在这种情况下,对每个缺少的键使用不同的空哈希