Skip to content

Instantly share code, notes, and snippets.

@leastbad
Forked from KonnorRogers/struct.rb
Created May 7, 2021 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leastbad/af89ecc40faf9c2df001095bf4203c83 to your computer and use it in GitHub Desktop.
Save leastbad/af89ecc40faf9c2df001095bf4203c83 to your computer and use it in GitHub Desktop.
Using hashes for structs
# 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