Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.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 on rails 在Ruby中创建新的哈希实例_Ruby On Rails_Ruby_Hash_Jruby_Jrubyonrails - Fatal编程技术网

Ruby on rails 在Ruby中创建新的哈希实例

Ruby on rails 在Ruby中创建新的哈希实例,ruby-on-rails,ruby,hash,jruby,jrubyonrails,Ruby On Rails,Ruby,Hash,Jruby,Jrubyonrails,我对Ruby很陌生,我正在Ruby中使用HashWithDisferenceAccess作为hash特性。所以我的代码是: def someFunction array_list = [] some_array.each do | x | new_hash = HashWithIndifferentAccess.new // add entries to new_hash array_list.push(new_hash)

我对Ruby很陌生,我正在Ruby中使用HashWithDisferenceAccess作为hash特性。所以我的代码是:

def someFunction
    array_list = []
    some_array.each do | x |
        new_hash = HashWithIndifferentAccess.new
        // add entries to new_hash    

        array_list.push(new_hash)
    end

    array_list
end
问题是:对于每个迭代,我都在初始化新的散列,但如果我执行以下操作,数组\列表中的条目将变为空:

def someFunction
    array_list = []
    new_hash = HashWithIndifferentAccess.new

    some_array.each do | x |
        // add entries to new_hash    

        array_list.push(new_hash)
        new_hash.clear
    end

    array_list
end
我不想为每次迭代初始化新的哈希,这个问题有什么解决方案吗

我不想为每次迭代初始化新的哈希

为什么不呢?这背后的原因是什么?你必须这样做,否则它就不能工作

如果不在每次迭代中创建新的哈希,则每次都将相同的哈希推送到数组中。数组中的每个元素都是相同的对象,共享相同的状态。只有一个散列,当您清除它时,对同一散列的所有引用显然也会被清除,因为它们都是相同的对象

这个问题有什么解决办法吗

是的,您已经有了它:您需要在每次迭代中创建一个新的哈希

我不想为每次迭代初始化新的哈希

为什么不呢?这背后的原因是什么?你必须这样做,否则它就不能工作

如果不在每次迭代中创建新的哈希,则每次都将相同的哈希推送到数组中。数组中的每个元素都是相同的对象,共享相同的状态。只有一个散列,当您清除它时,对同一散列的所有引用显然也会被清除,因为它们都是相同的对象

这个问题有什么解决办法吗

是的,您已经有了它:您需要在每次迭代中创建一个新哈希。

为什么[您]不想为每次迭代初始化新哈希?如果要向数组中添加多个哈希值,则必须这样做。为什么[您]不想为每次迭代初始化新哈希值?如果要向数组中添加多个哈希,则必须这样做。