Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created December 14, 2012 21:07
Show Gist options
  • Save havenwood/4288693 to your computer and use it in GitHub Desktop.
Save havenwood/4288693 to your computer and use it in GitHub Desktop.
Hash#to_struct
autoload :OpenStruct, 'ostruct'
class Hash
def to_struct struct_name
Object.const_set(struct_name, Struct.new(*keys)).new(*values)
end
def to_ostruct
OpenStruct.new self
end
end
menu = { breakfast: 'Green Eggs & Ham',
lunch: 'Bagel',
dinner: 'Ice Cream' }
menu = menu.to_struct :Meal
#=> #<struct Meal breakfast="Green Eggs & Ham", lunch="Bagel", dinner="Ice Cream">
menu.breakfast
#=> "Green Eggs & Ham"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment