Reputation: 341
I was searching on the internet for some easy interpretation of hashes in ruby but I haven`t found (let me know if you found). Thing is I am looking for a nice and efficient way to create hash values on the go. Here is my current example:
home = {}
home['rooms'] = {}
home['rooms']['kitchen'] = 'this is kitchen'
home['rooms']['hall'] = 'welcome in hall'
But this is really long interpretation. I am searching something similar in ruby to this:
home = {}
home['rooms']['kitchen'] = 'this is kitchen'
home['rooms']['kitchen']['some_parameter']['some_parameter2'] = 'random text'
I don`t want to define hash on the each step.
home['rooms'] = {}
home['rooms']['kitchen'] = {}
home['rooms']['kitchen']['some_parameter'] = {}
I hope it was clear what is my intent, if not I will answer in comments. During my code I would like to define new hashes. I don`t know the structure before, so idea is when I create new var[p1][p2][p3] it will be automatically created as hash and it it will not produce an error.
The thing is, those hashes keys can be created dynamically, from variable.
Upvotes: 1
Views: 429
Reputation: 114248
You can create a hash which uses another hash as its default value:
home = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }
home['rooms']['kitchen'] = 'this is kitchen'
home['rooms']['hall'] = 'welcome in hall'
home
#=> {"rooms"=>{"kitchen"=>"this is kitchen", "hall"=>"welcome in hall"}}
Passing default_proc
on to the inner hash ensures that you can nest it indefinitely:
home['foo']['bar']['baz'] = 'qux'
home
#=> {"rooms"=>{"kitchen"=>"this is kitchen", "hall"=>"welcome in hall"},
# "foo"=>{"bar"=>{"baz"=>"qux"}}}
Upvotes: 3
Reputation: 368
You can pass the entire hash (if you know the keys you want) when you instantiate the first one.
Something like this:
home = {
rooms: {
kitchen: '',
hall: ''
}
}
home[:rooms][:kitchen] = 'this is kitchen'
home[:rooms][:hall] = 'welcome in hall'
If you already have the values:
home = {
rooms: {
kitchen: 'this is kitchen',
hall: 'welcome in hall'
}
}
If you could provide a use case example, that would probably enable more precise answers.
EDIT:
If you want to access your keys with either String
or Symbol
:
home = {
rooms: {
kitchen: 'this is kitchen',
hall: 'welcome in hall'
}
}.with_indifferent_access
Upvotes: 0