F677fa685a2cfe8aff31f161062db3d3

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.

@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 !

D41d8cd98f00b204e9800998ecf8427e

john

December 9, 2008, December 09, 2008 07:51, permalink

1 rating. Login to rate!

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
D1535c766311cdf0dddf2269b6cd1120

Christoph Heindl

December 9, 2008, December 09, 2008 08:35, permalink

1 rating. Login to rate!

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
A8d3f35baafdaea851914b17dae9e1fc

Adam

December 9, 2008, December 09, 2008 17:53, permalink

2 ratings. Login to rate!
@appointments_by_day = (1..month_days).inject({}) do |appointments,day|
  (appointments[day] ||= []) << runt_object[1]
  appointments
end

Your refactoring





Format Copy from initial code

or Cancel