问题描述
我想用一个空的 Array
来初始化一个 Hash
,并且为每个新键推入一个特定的值数组。
以下是我试图做的:
a = Hash.new([])
#=> {}
a [1]<< asd
#=> [asd]
a
#=> {
a
的预期输出为 {1 => [asd]}
但没有发生。
Ruby版本:
ruby 2.0 .0p598(2014-11-13 revision 48408)[x86_64-linux]
只要做
a = Hash.new {| h,k | h [k] = []}
a [1]<< asd
a#=> {1 => [asd]}
从文档。这真的解释了为什么你没有得到所需的结果。
new(obj)→new_hash
$ b
new {| hash,key | block}→new_hash
您可以手动测试:
a = Hash.new([])
a [1] .object_id#=> 2160424560
a [2] .object_id#=> 2160424560
现在使用 Hash
对象创建时,您可以看到对未知键的每次访问,并返回相同的默认对象。现在另一种方式,我的意思是方式:
b = Hash.new {| h, K | []}
b [2] .object_id#=> 2168989980
b [1] .object_id#=> 2168933180
因此,通过 block 表单,每个未知键访问,返回一个新的 Array
对象。
I want to initialize a Hash
with an empty Array
and for every new key push a certain value to that array.
Here's what I tried to do:
a = Hash.new([])
# => {}
a[1] << "asd"
# => ["asd"]
a
# => {}
The expected output for a
was {1 => ["asd"]}
but that didn't happen. What am I missing here?
Ruby version:
ruby 2.0.0p598 (2014-11-13 revision 48408) [x86_64-linux]
Just do
a = Hash.new { |h, k| h[k] = [] }
a[1] << "asd"
a # => {1=>["asd"]}
Read the below lines from the Hash::new
documentation. It really explains why you didn't get the desired result.
new(obj) → new_hash
new {|hash, key| block } → new_hash
You can test by hand :
a = Hash.new([])
a[1].object_id # => 2160424560
a[2].object_id # => 2160424560
Now with the above style of Hash
object creation, you can see every access to an unknown key, returning back the same default object. Now the other way, I meant block way :
b = Hash.new { |h, k| [] }
b[2].object_id # => 2168989980
b[1].object_id # => 2168933180
So, with the block form, every unknown key access, returning a new Array
object.
这篇关于用空数组意外行为初始化一个Hash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!