Class: Cape::HashList
- Inherits:
-
Array
- Object
- Array
- Cape::HashList
- Defined in:
- lib/cape/hash_list.rb
Overview
A HashList is a collection of key-value pairs. It is similar to an Array, except that indexing is done via arbitrary keys of any object type, not an integer index. Hashes enumerate their values in the order that the corresponding keys were inserted.
This class exists because in Ruby v1.8.7 and earlier, Hash did not preserve the insertion order of keys.
Instance Method Summary collapse
-
#==(other) ⇒ true, false
Compares a HashList to another object.
-
#[](key) ⇒ Object?
Retrieves a value from the HashList.
-
#[]=(key, value) ⇒ HashList
Sets a value in the HashList.
-
#initialize(*arguments) ⇒ HashList
constructor
Constructs a new HashList using the specified arguments.
-
#inspect ⇒ String
Provides a string representation of the HashList.
-
#to_hash ⇒ Hash
Converts the HashList to a Hash.
Constructor Details
#initialize(*arguments) ⇒ HashList
Constructs a new HashList using the specified arguments.
15 16 17 |
# File 'lib/cape/hash_list.rb', line 15 def initialize(*arguments) super Hash[*arguments].to_a end |
Instance Method Details
#==(other) ⇒ true, false
Compares a HashList to another object.
26 27 28 |
# File 'lib/cape/hash_list.rb', line 26 def ==(other) other.is_a?(::Hash) ? (other == to_hash) : super(other) end |
#[](key) ⇒ Object?
Retrieves a value from the HashList.
36 37 38 39 40 41 |
# File 'lib/cape/hash_list.rb', line 36 def [](key) entry = find do |pair| Array(pair).first == key end entry ? Array(entry).last : nil end |
#[]=(key, value) ⇒ HashList
Sets a value in the HashList.
49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/cape/hash_list.rb', line 49 def []=(key, value) index = find_index do |pair| Array(pair).first == key end if index super key, value else self << [key, value] end self end |
#inspect ⇒ String
Provides a string representation of the HashList.
64 65 66 67 68 69 |
# File 'lib/cape/hash_list.rb', line 64 def inspect entries = collect do |pair| Array(pair).collect(&:inspect).join '=>' end "{#{entries.join ', '}}" end |
#to_hash ⇒ Hash
Converts the HashList to a Hash.
74 75 76 |
# File 'lib/cape/hash_list.rb', line 74 def to_hash ::Hash[to_a] end |