Hashes in ruby don't by default give you these dot methods.
You can chain send calls (this works on any object, but you can't access hash keys in this way normally):
"foo".send(:downcase).send(:upcase)
When working with nested hashes the tricky concept of mutability is relevant. For example:
hash = { a: { b: { c: 1 } } }
nested = hash[:a][:b]
nested[:b] = 2
hash
# => { a: { b: { c: 2 } }
"Mutability" here means that when you store the nested hash into a separate variable, it's still actually a pointer to the original hash. Mutability is useful for a situation like this but it can also create bugs if you don't understand it.
You can assign :a
or :b
to variables to make it 'dynamic' in a sense.
There are more advanced ways to do this, such as dig
in newer Ruby
versions.
hash = { a: { b: { c: 1 } } }
keys_to_get_nested_hash = [:a, :b]
nested_hash = hash.dig *keys_to_get_nested_hash
nested_hash[:c] = 2
hash
# => { a: { b: { c: 2 } } }
If you use OpenStruct
then you can give your hashes dot-method accessors. To be honest chaining send
calls is not something I've used often. If it helps you write code, that's great. But you shouldn't be sending user-generated input, because it's insecure.