Class: Plutonium::Lib::OverlayedHash
- Inherits:
-
Object
- Object
- Plutonium::Lib::OverlayedHash
- Defined in:
- lib/plutonium/lib/overlayed_hash.rb
Overview
OverlayedHash provides a hash-like structure that overlays values on top of a base hash.
This class allows you to create a new hash-like object that uses a base hash for default values, but can be modified without affecting the original base hash. When a key is accessed, it first checks if the key exists in the overlay; if not, it falls back to the base hash.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Retrieve a value from the overlay hash or the base hash.
-
#[]=(key, value) ⇒ Object
Set a value in the overlay hash.
-
#each_key {|key| ... } ⇒ Enumerator
Enumerate over all keys in both the overlay and base hash.
-
#initialize(base) ⇒ OverlayedHash
constructor
Initialize a new OverlayedHash with a base hash.
-
#key?(key) ⇒ Boolean
Check if a key exists in either the overlay or base hash.
-
#keys ⇒ Array
Retrieve all keys from both the overlay and base hash.
-
#to_h ⇒ Hash
Convert the OverlayedHash to a regular Hash.
-
#values ⇒ Array
Retrieve all values, prioritizing the overlay over the base.
Constructor Details
#initialize(base) ⇒ OverlayedHash
Initialize a new OverlayedHash with a base hash.
25 26 27 28 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 25 def initialize(base) @base = base = {} end |
Instance Method Details
#[](key) ⇒ Object
Retrieve a value from the overlay hash or the base hash.
34 35 36 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 34 def [](key) .key?(key) ? [key] : @base[key] end |
#[]=(key, value) ⇒ Object
Set a value in the overlay hash.
42 43 44 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 42 def []=(key, value) [key] = value end |
#each_key {|key| ... } ⇒ Enumerator
Enumerate over all keys in both the overlay and base hash.
58 59 60 61 62 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 58 def each_key return to_enum(:each_key) unless block_given? keys.each { |key| yield key } end |
#key?(key) ⇒ Boolean
Check if a key exists in either the overlay or base hash.
50 51 52 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 50 def key?(key) .key?(key) || @base.key?(key) end |
#keys ⇒ Array
Retrieve all keys from both the overlay and base hash.
67 68 69 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 67 def keys (.keys + @base.keys).uniq end |
#to_h ⇒ Hash
Convert the OverlayedHash to a regular Hash.
81 82 83 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 81 def to_h keys.each_with_object({}) { |key, hash| hash[key] = self[key] } end |
#values ⇒ Array
Retrieve all values, prioritizing the overlay over the base.
74 75 76 |
# File 'lib/plutonium/lib/overlayed_hash.rb', line 74 def values keys.map { |key| self[key] } end |