如何在给定元素后将新值插入有序哈希?

时间:2012-12-13 08:52:13

标签: ruby hash

我想使用有序哈希。

existing_hash = { key: value1, foo: value2 }

I want add { bar: value3 } after key 'key:'
expecting_hash = { key: value1, bar: value3, foo: value2 }

我的代码:

existing_hash[:bar] = value3
actual_hash =  { key: value1, foo: value2, bar: value3 }

1 个答案:

答案 0 :(得分:0)

@Sergio对于Hash的无序性质是正确的,但从技术上讲,它看起来很有趣。

无法避免找到解决方案:)

虽然不是很优雅,但它是这样的:

# having this and need to insert 3 after 2
h = {1=>:one, 2=>:two, 4=>:four, 5=>:five}

after_key = 2
after_key_index = h.keys.index(after_key)
h1,h2 = h.partition {|k,v| h.keys.index(k) <= after_key_index }.map {|a| Hash[a]}

p h1.merge(3 => :three).merge(h2)
# => {1=>:one, 2=>:two, 3=>:three, 4=>:four, 5=>:five}

# or

h1[3] = :three
p h1.merge h2
# => {1=>:one, 2=>:two, 3=>:three, 4=>:four, 5=>:five}

并应用于您的代码:

h = { key: :value1, foo: :value2 }

after_key = :key
after_key_index = h.keys.index(after_key)
h1,h2 = h.partition {|k,v| h.keys.index(k) <= after_key_index }.map {|a| Hash[a]}

p h1.merge(:bar => :value3).merge(h2)
# => {:key=>:value1, :bar=>:value3, :foo=>:value2}

# or

h1[:bar] = :value3
p h1.merge h2
# => {:key=>:value1, :bar=>:value3, :foo=>:value2}