Hashのエントリの順序を操作するhash_order_helperを作った

Hashのエントリの順序を破壊的に更新したいということが希によくあるので、エントリの順序をArrayのように操作できるメソッドを追加するhash_order_helperを作った。

github.com

以下のような感じで、Hashのエントリの順序を操作できる。

require 'hash_order_helper'

hash = {b: 200, a: 100, c: 150}

hash.sort_pair
#=> {:a=>100, :b=>200, :c=>150}

hash.unshift(d: 300)
#=> {:d=>300, :b=>200, :a=>100, :c=>150}

追加されるメソッドは以下の通り。

  • sort_pair -> Hash
  • sort_pair! -> Hash
  • sort_pair_by {|key, value| ... } -> Hash
  • sort_pair_by! {|key, value| ... } -> Hash
  • at(nth) -> Array
  • insert(nth, hash) -> Hash
  • last -> Array
  • last(n) -> Array
  • pop -> Array
  • pop(n) -> Array
  • push(key, hash) -> Hash
  • unshift(key, hash) -> Hash