[英]Array conversion to hash
I'm confused as to this behavior. 我对这种行为感到困惑。 Do I really need to split my array to make this work?
我是否真的需要拆分我的阵列以使其工作?
pry(main)> ary = ["foo", "bar"]
=> ["foo", "bar"]
pry(main)> Hash[ary]
=> {"f"=>"o", "b"=>"a"}
pry(main)> Hash["foo", "bar"]
=> {"foo"=>"bar"}
pry(main)> Hash[["foo", "bar"]]
=> {"f"=>"o", "b"=>"a"}
pry(main)> Hash[ary.split(",")]
=> {"foo"=>"bar"}
Tries 1 and 3 above are equivalent, passing a single one dimensional array to the constructor, which is not correct. 上面的尝试1和3是等效的,将单个一维数组传递给构造函数,这是不正确的。
For this to work as you expect, you'd need to pass the parameters as separate arguments, or as a 2 dimensional array of pairs> 为了使其按预期工作,您需要将参数作为单独的参数传递,或者作为二维数组>传递
# Split the array into args (equivalent to example #2 above)
# equivalent to Hash[key1, val1, key2, val2]
Hash[*ary]
# or wrap the array in another array (an array of nested pairs)
# equivalent to Hash[[[key1,val1],[key2,val2]]]
Hash[[ary]]
The incorrect behavior you're seeing is presumably because the constructor expects an array of length-2 arrays, while you've passed an array of strings. 您所看到的错误行为可能是因为构造函数需要一个长度为2的数组数组,而您传递了一个字符串数组。 It interprets
arg[0]
as the key for each pair, and arg[1]
as the value, in this case f
and o
, b
and a
. 它将
arg[0]
解释为每对的关键,并将arg[1]
为值,在本例中为f
和o
, b
和a
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.