Class: Hash
- Inherits:
-
Object
- Object
- Hash
- Defined in:
- lib/dorian/to_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"
40 41 42 43 44 45 46 |
# File 'lib/dorian/to_struct.rb', line 40 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...>
31 32 33 |
# File 'lib/dorian/to_struct.rb', line 31 def to_struct Struct.new(*keys.map(&:to_sym)).new(*values) end |