数组转换为哈希

发布于 2024-12-11 07:38:24 字数 366 浏览 0 评论 0原文

我对这种行为感到困惑。我真的需要拆分我的数组才能完成这项工作吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

护你周全 2024-12-18 07:38:24

上面的尝试 1 和 3 是等效的,将单个一维数组传递给构造函数,这是不正确的。

为了使其按照您的预期工作,您需要将参数作为单独的参数传递,或者作为对的二维数组传递>

# 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]]

您看到的不正确行为可能是因为构造函数需要一个长度为 2 的数组,而您传递了一个字符串数组。它将 arg[0] 解释为每对的键,将 arg[1] 解释为值,在本例中为 foba

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>

# 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. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文