-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 に答える