Example as follows:
if house['windows'][floor_1]
house['windows'][floor_1] << north_side
else
house['windows'][floor_1] = [north_side]
end
Best way to check for existing key?
Example as follows:
if house['windows'][floor_1]
house['windows'][floor_1] << north_side
else
house['windows'][floor_1] = [north_side]
end
Best way to check for existing key?
The fact that house['windows']
is an element in a hash already is a bit of a red herring, so I will use windows
as a variable referencing a hash.
Set up a default value for the windows
hash, so that any non-preexisting key is assigned an array value:
windows = Hash.new {|hash, key| hash[key] = [] }
Now you can append (<<
) to new hash elements automatically.
windows['floor_1'] << 'north_side'
windows # => {"floor_1"=>["north_side"]}
For your specific case, replace windows
with house['windows']
.
EDIT
As pointed out in the comments, this behavior can be added to an already-instantiated hash:
windows.default_proc = proc {|hash, key| hash[key] = [] }
I would do something like:
house['windows'][floor_1] ||= []
house['windows'][floor_1] << north_side
Given your Hash, I imagine:
house = { windows: { floor_0: ['f0'] } }
You can check the existence of a key using Hash#has_key?
house[:windows].has_key? :floor_1 #=> false
So you can create it:
house[:windows].merge!({floor_1: []}) unless house[:windows].has_key? :floor_1
Hash#default_proc=
:
house[:windows].default_proc = proc { |h, k| h[k] = [] }
So you can
house[:windows][:floor_3] << 'f3'
house #=> {:windows=>{:floor_0=>["f0"], :floor_1=>[], :floor_3=>["f3"]}}