@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}