-
-
Save leastbad/af89ecc40faf9c2df001095bf4203c83 to your computer and use it in GitHub Desktop.
Using hashes for structs
This file contains hidden or 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
# using a predefined hash | |
hash = { field1: "foo", field2: "bar" } | |
HashStruct = Struct.new(*hash.keys, keyword_init: true) | |
hash_struct = HashStruct.new(hash) | |
hash_struct.field1 # => "foo" | |
hash_struct.field2 # => "bar" | |
hash_struct.field3 # => ERROR! | |
# using an array | |
ary = [:field1, :field2] | |
AryStruct = Struct.new(*ary, keyword_init: true) | |
ary_hash = {} | |
ary_hash[:field1] = "foo" | |
ary_hash[:field2] = "bar" | |
ary_struct = AryStruct.new(ary_hash) | |
ary_struct.field1 # => "foo" | |
ary_struct.field2 # => "bar" | |
ary_struct.field3 # => ERROR! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment