Skip to content

Instantly share code, notes, and snippets.

@KonnorRogers
Last active June 17, 2021 14:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save KonnorRogers/1dc0038b4a31fdddff39748770851be1 to your computer and use it in GitHub Desktop.
Save KonnorRogers/1dc0038b4a31fdddff39748770851be1 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!
@sajanbasnet75
Copy link

Thanks for the gist. I have one question

hash = { 'company' => [{ 'name' => 'Company1', 'departments': [{ 'name' => 'Management' }] },
                       { 'name' => 'Company2', 'departments': [{ 'name' => 'Engineering' }] }] }

How can we create a Struct class for above-nested Hash? so that we can access like "company.first.departments.first"

@KonnorRogers
Copy link
Author

@sajanbasnet75 I havent really thought aboutt this use case too much. I really only thought about top-level objects.

For a nested hash to use dot notation, if youre using Rails, you could do something like this:

h = ActiveSupport::InheritableOptions.new({ 'company' => [{ 'name' => 'Company1', 'departments': [{ 'name' => 'Management' }] },
                                                                                                    { 'name' => 'Company2', 'departments': [{ 'name' => 'Engineering' }] }] )})

which then allows you to do:

h.company.first.departments.first

@sajanbasnet75
Copy link

sajanbasnet75 commented Jun 17, 2021

Thanks for the reply @ParamagicDev

Unfortunately, I am trying to do this on plain ruby, also using Struct rather than openStruct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment