Ruby重新组织哈希

时间:2013-11-18 17:05:05

标签: ruby-on-rails ruby hash

我正在尝试重新组织哈希,以便特定键位于开头,另一个键位于结尾。例如:

x = {:a => 123, :b => 456, :c => 789, :d => 123}
# returns => {:a=>123, :b=>456, :c=>789, :d=>123}
x.sort.reverse!
# returns => [[:d, 123], [:c, 789], [:b, 456], [:a, 123]] 

如何使用c开始散列,并在排序后以b结尾?

编辑:我需要订购哈希,因为当我执行“x.each | key,object | do ...”时,我需要哈希以特定键开头

3 个答案:

答案 0 :(得分:2)

x = {:a => 123, :b => 456, :c => 789, :d => 123}

c, b = x.delete(:c), x.delete(:b)
Hash[[[:c, c], *x.sort.reverse, [:b, b]]]
# => {:c => 789, :d => 123, :a => 123, :b => 456}

c, b = x.delete(:c), x.delete(:b)
Hash[:c, c, *x.sort.reverse.flatten, :b, b]
# => {:c => 789, :d => 123, :a => 123, :b => 456}

答案 1 :(得分:2)

不要依赖哈希秩序。获取密钥,订购密钥并循环哈希:

keys = x.keys
#sort how you need it
keys.each do |key|
  object = x[key]
  #do what you want
end

答案 2 :(得分:-2)

由于Ruby 1.9哈希保持其顺序(尽管==运算符忽略了这一点)。问题是大多数这些方法早于1.9,它们用于返回一个数组。您可以通过以下方式轻松地从配对值数组创建哈希:

x = {c: 1, d: 2, a: 3, b: 4}

x.sort.reverse
#=> [[:d, 2], [:c, 1], [:b, 4], [:a, 3]]

Hash[x.sort.reverse]
#=> {:d=>2, :c=>1, :b=>4, :a=>3}