Hash with preserved order and some array-like extensions.

Usage

Just require this file and use OrderedHash instead of Hash.

  require 'hash/ordered'

  # You can do simply
  hsh = Hash::Ordered.new
  hsh['z'] = 1
  hsh['a'] = 2
  hsh['c'] = 3
  p hsh.keys     #=> ['z','a','c']

  # or using OrderedHash[] method
  hsh = OrderedHash['z', 1, 'a', 2, 'c', 3]
  p hsh.keys     #=> ['z','a','c']

  # but this don't preserve order
  hsh = OrderedHash['z'=>1, 'a'=>2, 'c'=>3]
  p hsh.keys     #=> ['a','c','z']

  # OrderedHash has useful extensions: push, pop and unshift
  p hsh.push('to_end', 15)       #=> true, key added
  p hsh.push('to_end', 30)       #=> false, already - nothing happen
  p hsh.unshift('to_begin', 50)  #=> true, key added
  p hsh.unshift('to_begin', 60)  #=> false, already - nothing happen
  p hsh.keys                     #=> ["to_begin", "a", "c", "z", "to_end"]
  p hsh.pop                      #=> ["to_end", 15], if nothing remains, return nil
  p hsh.keys                     #=> ["to_begin", "a", "c", "z"]
  p hsh.shift                    #=> ["to_begin", 30], if nothing remains, return nil

Author(s)

  • jan molic </mig/at/1984/dot/cz/>

Special Thanks

Andrew Johnson for his suggestions and fixes of Hash[], merge, to_a, inspect and shift.

Methods
Attributes
[RW] order
Public Class methods
[](*args) [ source ]
new() [ source ]
Public Instance methods
==(hsh2) [ source ]
[]=(a,b)

Alias for store

clear() [ source ]
delete(key) [ source ]
delete_if() {|| ...} [ source ]
each() {|k,self[k]| ...} [ source ]
This method is also aliased as each_pair
each_key() {|k| ...} [ source ]
each_pair()

Alias for each

each_value() {|self[k]| ...} [ source ]
inspect() [ source ]
invert() [ source ]
keys() [ source ]
merge(hsh2) [ source ]
merge!(hsh2)

Alias for update

pop() [ source ]
push(k,v) [ source ]
reject(&block) [ source ]
reject!(&block) [ source ]
replace(hsh2) [ source ]
select() {|k,v| ...} [ source ]
shift() [ source ]
store(a,b) [ source ]
This method is also aliased as []=
store_only(a,b) [ source ]
to_a() [ source ]
to_s() [ source ]
unshift(k,v) [ source ]
update(hsh2) [ source ]
This method is also aliased as merge!
values() [ source ]