Ruby 哈希排列
有没有快速的方法来获得给定哈希的(随机)排列?例如,对于数组,我可以使用 sample 方法作为对于
ruby-1.9.2-p180 :031 > a = (1..5).to_a
=> [1, 2, 3, 4, 5]
ruby-1.9.2-p180 :032 > a.sample(a.length)
=> [3, 5, 1, 2, 4]
哈希,我可以在哈希键上使用相同的方法并构建一个新的哈希,
ruby-1.9.2-p180 :036 > h = { 1 => 'a', 2 => 'b', 3 => 'c' }
=> {1=>"a", 2=>"b", 3=>"c"}
ruby-1.9.2-p180 :037 > h.keys.sample(h.length).inject({}) { |h2, k| h2[k] = h[k]; h2 }
=> {3=>"c", 2=>"b", 1=>"a"}
但这太丑陋了。是否有任何可以避免所有代码的哈希“样本”方法?
更新 正如@Michael Kohl 在评论中指出的,这个问题仅对 ruby 1.9.x 有意义。由于在 1.8.x 中哈希是无序的,因此无法做到这一点。
Is there any quick way to get a (random) permutation of a given hash? For example with arrays I can use the sample method as in
ruby-1.9.2-p180 :031 > a = (1..5).to_a
=> [1, 2, 3, 4, 5]
ruby-1.9.2-p180 :032 > a.sample(a.length)
=> [3, 5, 1, 2, 4]
For hashes I can use the same method on hash keys and build a new hash with
ruby-1.9.2-p180 :036 > h = { 1 => 'a', 2 => 'b', 3 => 'c' }
=> {1=>"a", 2=>"b", 3=>"c"}
ruby-1.9.2-p180 :037 > h.keys.sample(h.length).inject({}) { |h2, k| h2[k] = h[k]; h2 }
=> {3=>"c", 2=>"b", 1=>"a"}
but this is so ugly. Is there any 'sample' method for hashes which can avoid all that code?
Update As pointed out by @Michael Kohl in comments, this question is meaningful only for ruby 1.9.x. Since in 1.8.x Hash are unordered there is no way to do that.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
mu 的稍微细化太短了答案:
A slight refinement of mu is too short's answer:
只需添加
to_a
和哈希[]
到你的数组版本以获得哈希版本:例如:
Just add a
to_a
andHash[]
to your array version to get a Hash version:For example:
您真的需要随机播放还是只需要一种访问/迭代随机密钥的方法?
否则,一个可能更便宜的解决方案是对散列键进行洗牌,并根据这些散列键的排列来访问您的项目,
我相信(但需要带有基准的证明),这避免了构建全新的需要/成本哈希,如果你有大哈希,可能会更有效(你只需要支付数组排列的成本)
Do you really need to shuffle or do you just need a way to access/iterate on a random key ?
Otherwise, a maybe less expensive solution would be to shuffle the hash keys and access your items based on the permutation of those hash keys
I believe (but would need a proof with a benchmark) that this avoids the need/cost to build a brand new hash and is probably more efficient if you have big hashes (you only need to pay the cost of an array permutation)