@appointments_by_day = {}
day_counter = 1
#runt_objects is an array
while(day_counter <= month_days)
unless @appointments_by_day[day_counter]
@appointments_by_day[day_counter] = Array.new
@appointments_by_day[day_counter].push(runt_object[1])
#new helper function here
else
@appointments_by_day[day_counter].push(runt_object[1])
end
day_counter += 1
end
Refactorings
No refactoring yet !
john
December 9, 2008, December 09, 2008 07:51, permalink
Hash allows you to provide a "default" procedure to be executed when a key is used that is not already in the hash.
@appointments_by_day = Hash.new { |hash, key| hash[key] = [] }
day_counter = 1
#runt_objects is an array
while day_counter <= month_days
@appointments_by_day[day_counter].push(runt_object[1])
day_counter += 1
end
Christoph Heindl
December 9, 2008, December 09, 2008 08:35, permalink
Here is another idiom (just for completion): the Hash#[]= operation returns the value you've just assigned to it. So you might do the following
@appointments_by_day = {}
day_counter = 1
#runt_objects is an array
while day_counter <= month_days
entry = @appointments_by_day[day_counter] || @appointments_by_day[day_counter] = []
entry << runt_object[1]
day_counter += 1
end
I am trying to add arrays to a hash, but am having trouble finding an elegant way to create a new array if it does not exist in the hash, or just add the element to the array if it already exists. I'm thinking there is a better way to do this using ||? I have only included the relevant code.