Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/dorian/core_ext/hash/struct.rb
Instance Method Summary collapse
-
#to_deep_struct ⇒ Object
Returns a new struct with the same key/value pairs.
-
#to_struct ⇒ Object
Returns a new struct with the same key/value pairs.
Instance Method Details
#to_deep_struct ⇒ Object
Returns a new struct with the same key/value pairs
user = { name: "Dorian", events: [{ name: "Party" }] }.to_deep_struct
user.events.first.name # => "Party"
19 20 21 22 23 24 25 |
# File 'lib/dorian/core_ext/hash/struct.rb', line 19 def to_deep_struct Struct.new(*keys.map(&:to_sym)).new( *values.map do |value| value.respond_to?(:to_deep_struct) ? value.to_deep_struct : value end ) end |
#to_struct ⇒ Object
Returns a new struct with the same key/value pairs
user = { first_name: "Dorian", last_name: "Marié" }.to_struct
user.first_name # => "Dorian"
user.birthdate # => NoMethodError: undefined method `birthdate' for <struct...>
10 11 12 |
# File 'lib/dorian/core_ext/hash/struct.rb', line 10 def to_struct Struct.new(*keys.map(&:to_sym)).new(*values) end |