Class: Kramdown::Utils::OrderedHash
- Inherits:
-
Object
- Object
- Kramdown::Utils::OrderedHash
- Includes:
- Enumerable
- Defined in:
- lib/kramdown/utils/ordered_hash.rb
Overview
A partial hash implementation which preserves the insertion order of the keys.
Note that this class is only used on Ruby 1.8 since the built-in Hash on Ruby 1.9 automatically preserves the insertion order. However, to remain compatibility only the methods defined in this class may be used when working with OrderedHash on Ruby 1.9.
Instance Method Summary collapse
-
#==(other) ⇒ Object
:nodoc:.
-
#[](key) ⇒ Object
Return the value for the
key
. -
#[]=(key, val) ⇒ Object
Set the value for the
key
toval
. -
#delete(key) ⇒ Object
Delete the
key
. -
#dup ⇒ Object
:nodoc:.
-
#each ⇒ Object
Iterate over the stored keys in insertion order.
-
#has_key?(key) ⇒ Boolean
Return
true
if the hash contains the key. -
#initialize ⇒ OrderedHash
constructor
Initialize the OrderedHash object.
-
#inspect ⇒ Object
:nodoc:.
- #merge!(other) ⇒ Object
Constructor Details
#initialize ⇒ OrderedHash
Initialize the OrderedHash object.
39 40 41 42 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 39 def initialize @data = {} @order = [] end |
Instance Method Details
#==(other) ⇒ Object
:nodoc:
83 84 85 86 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 83 def ==(other) #:nodoc: return false unless other.kind_of?(self.class) @data == other.instance_variable_get(:@data) && @order == other.instance_variable_get(:@order) end |
#[](key) ⇒ Object
Return the value for the key
.
50 51 52 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 50 def [](key) @data[key] end |
#[]=(key, val) ⇒ Object
Set the value for the key
to val
.
60 61 62 63 |
# File 'lib/kramdown/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/kramdown/utils/ordered_hash.rb', line 66 def delete(key) @order.delete(key) @data.delete(key) end |
#dup ⇒ Object
:nodoc:
76 77 78 79 80 81 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 76 def dup #:nodoc: new_object = super new_object.instance_variable_set(:@data, @data.dup) new_object.instance_variable_set(:@order, @order.dup) new_object end |
#each ⇒ Object
Iterate over the stored keys in insertion order.
45 46 47 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 45 def each @order.each {|k| yield(k, @data[k])} end |
#has_key?(key) ⇒ Boolean
Return true
if the hash contains the key.
55 56 57 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 55 def has_key?(key) @data.has_key?(key) end |
#inspect ⇒ Object
:nodoc:
88 89 90 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 88 def inspect #:nodoc: "{" + map {|k,v| "#{k.inspect}=>#{v.inspect}"}.join(" ") + "}" end |
#merge!(other) ⇒ Object
71 72 73 74 |
# File 'lib/kramdown/utils/ordered_hash.rb', line 71 def merge!(other) other.each {|k,v| self[k] = v} self end |