Last active
June 17, 2021 14:53
-
-
Save KonnorRogers/1dc0038b4a31fdddff39748770851be1 to your computer and use it in GitHub Desktop.
Using hashes for structs
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
# 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 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
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
Thanks for the gist. I have one question
How can we create a Struct class for above-nested Hash? so that we can access like "company.first.departments.first"