Created
December 14, 2012 21:07
-
-
Save havenwood/4288693 to your computer and use it in GitHub Desktop.
Hash#to_struct
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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