Class: Newstile::Utils::OrderedHash
- Inherits:
-
Object
- Object
- Newstile::Utils::OrderedHash
- Includes:
- Enumerable
- Defined in:
- lib/newstile/utils/ordered_hash.rb
Overview
A very simple class mimicking the most used methods of a Hash. The difference to a normal Hash is that a OrderedHash retains the insertion order of the keys.
Instance Attribute Summary collapse
-
#data ⇒ Object
readonly
Direct access to the hash with the key-value pairs.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Return the value for the
key
. -
#[]=(key, val) ⇒ Object
Set the value for the
key
toval
. -
#delete(key) ⇒ Object
Delete the
key
. -
#each ⇒ Object
Iterate over the stored keys in insertion order.
-
#initialize(hash = {}) ⇒ OrderedHash
constructor
Initialize the OrderedHash object, optionally with an
hash
. -
#inspect ⇒ Object
:nodoc:.
Constructor Details
#initialize(hash = {}) ⇒ OrderedHash
Initialize the OrderedHash object, optionally with an hash
. If the optional hash
is used, there is no special order imposed on the keys (additionally set keys will be stored in insertion order). An OrderedHash object may be used instead of a hash to provide the initial data.
40 41 42 43 44 45 46 47 |
# File 'lib/newstile/utils/ordered_hash.rb', line 40 def initialize(hash = {}) if hash.kind_of?(OrderedHash) @data, @order = hash.instance_eval { [@data.dup, @order.dup] } else @data = hash || {} @order = @data.keys end end |
Instance Attribute Details
#data ⇒ Object (readonly)
Direct access to the hash with the key-value pairs. May not be used to modify the data!
34 35 36 |
# File 'lib/newstile/utils/ordered_hash.rb', line 34 def data @data end |
Instance Method Details
#[](key) ⇒ Object
Return the value for the key
.
55 56 57 |
# File 'lib/newstile/utils/ordered_hash.rb', line 55 def [](key) @data[key] end |
#[]=(key, val) ⇒ Object
Set the value for the key
to val
.
60 61 62 63 |
# File 'lib/newstile/utils/ordered_hash.rb', line 60 def []=(key, val) @order << key if !@data.has_key?(key) @data[key] = val end |
#delete(key) ⇒ Object
Delete the key
.
66 67 68 69 |
# File 'lib/newstile/utils/ordered_hash.rb', line 66 def delete(key) @order.delete(key) @data.delete(key) end |
#each ⇒ Object
Iterate over the stored keys in insertion order.
50 51 52 |
# File 'lib/newstile/utils/ordered_hash.rb', line 50 def each @order.each {|k| yield(k, @data[k])} end |
#inspect ⇒ Object
:nodoc:
71 72 73 |
# File 'lib/newstile/utils/ordered_hash.rb', line 71 def inspect #:nodoc: "{" + map {|k,v| "#{k.inspect}=>#{v.inspect}"}.join(" ") + "}" end |