Class: Hash
- Defined in:
- lib/shenanigans/hash/extract.rb,
lib/shenanigans/hash/to_ostruct.rb,
lib/shenanigans/hash/has_shape_pred.rb
Instance Method Summary collapse
-
#extract(*ks) ⇒ Object
Returns a new hash only with the specified keys (if present).
-
#has_shape?(shape) ⇒ Boolean
Checks if a hash has a certain structure.
-
#to_ostruct ⇒ Object
Recursively converts a
Hash
and all nestedHash
es toOpenStruct
s.
Instance Method Details
#extract(*ks) ⇒ Object
Returns a new hash only with the specified keys (if present).
9 10 11 12 |
# File 'lib/shenanigans/hash/extract.rb', line 9 def extract(*ks) existing = keys & ks Hash[existing.zip(values_at(*existing))] end |
#has_shape?(shape) ⇒ Boolean
Checks if a hash has a certain structure.
12 13 14 15 16 |
# File 'lib/shenanigans/hash/has_shape_pred.rb', line 12 def has_shape?(shape) all? do |k, v| Hash === v ? v.has_shape?(shape[k]) : shape[k] === v end end |
#to_ostruct ⇒ Object
Recursively converts a Hash
and all nested Hash
es to OpenStruct
s. Especially useful for parsing YAML.
22 23 24 25 26 27 28 29 30 31 32 33 34 |
# File 'lib/shenanigans/hash/to_ostruct.rb', line 22 def to_ostruct arr = map { |k, v| case v when Hash [k, v.to_ostruct] when Array [k, v.map { |el| el.respond_to?(:to_ostruct) ? el.to_ostruct : el }] else [k, v] end } OpenStruct.new(Hash[arr]) end |