Created
March 25, 2019 15:02
-
-
Save localhostdotdev/daeb12e4af2bfedbb6f18f2c5c7b7a86 to your computer and use it in GitHub Desktop.
Struct.from_hash: the best of Struct and OpenStruct combined :)
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
class Struct | |
def self.from_hash(attributes) | |
new(*attributes.keys).new(*attributes.values) | |
end | |
end | |
user = Struct.from_hash(id: 1, name: "?") | |
user.id # => 1 | |
user.names # => NoMethodError (undefined method `names' for #<struct id=1, name="?">) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment