-1

我想使用有序哈希。

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

1 回答 1

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}
于 2012-12-13T09:34:33.903 回答