Hashのエントリの順序を破壊的に更新したいということが希によくあるので、エントリの順序をArrayのように操作できるメソッドを追加するhash_order_helperを作った。
以下のような感じで、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 -> Hashsort_pair! -> Hashsort_pair_by {|key, value| ... } -> Hashsort_pair_by! {|key, value| ... } -> Hashat(nth) -> Arrayinsert(nth, hash) -> Hashlast -> Arraylast(n) -> Arraypop -> Arraypop(n) -> Arraypush(key, hash) -> Hashunshift(key, hash) -> Hash