数组转换为哈希
我对这种行为感到困惑。我真的需要拆分我的数组才能完成这项工作吗?
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"}
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"}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
上面的尝试 1 和 3 是等效的,将单个一维数组传递给构造函数,这是不正确的。
为了使其按照您的预期工作,您需要将参数作为单独的参数传递,或者作为对的二维数组传递>
您看到的不正确行为可能是因为构造函数需要一个长度为 2 的数组,而您传递了一个字符串数组。它将
arg[0]
解释为每对的键,将arg[1]
解释为值,在本例中为f
和o
、b
和a
。Tries 1 and 3 above are equivalent, passing a single one dimensional array to the constructor, which is not correct.
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>
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. It interprets
arg[0]
as the key for each pair, andarg[1]
as the value, in this casef
ando
,b
anda
.