Class: Cape::HashList

Inherits:
Array
  • Object
show all
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

Constructor Details

#initialize(*arguments) ⇒ HashList

Constructs a new HashList using the specified arguments.

Parameters:

  • arguments (Hash)

    attribute values



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.

Parameters:

  • other (Object)

    another object

Returns:

  • (true)

    the HashList has the same number of keys as other, and each key-value pair is equal (according to Object#==)

  • (false)

    the HashList is not equal to other



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.

Parameters:

  • key (Object)

    a key

Returns:

  • (Object)

    the value for key

  • (nil)

    if there is no value for key



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.

Parameters:

  • key (Object)

    a key

  • value (Object)

    a value for key

Returns:



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

#inspectString

Provides a string representation of the HashList.

Returns:

  • (String)

    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_hashHash

Converts the HashList to a Hash.

Returns:

  • (Hash)

    a hash



74
75
76
# File 'lib/cape/hash_list.rb', line 74

def to_hash
  ::Hash[to_a]
end