Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
lib/dorian-to_struct.rb

Instance Method Summary collapse

Instance Method Details

#to_deep_structObject

Returns a new struct with the same key/value pairs

user = { name: "Dorian", events: [{ name: "Party" }] }.to_deep_struct
user.events.first.name # => "Party"


42
43
44
45
46
47
48
# File 'lib/dorian-to_struct.rb', line 42

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_structObject

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...>


33
34
35
# File 'lib/dorian-to_struct.rb', line 33

def to_struct
  Struct.new(*keys.map(&:to_sym)).new(*values)
end