Which of these Array Initializations is better in Ruby?
        Posted  
        
            by Bragaadeesh
        on Stack Overflow
        
        See other posts from Stack Overflow
        
            or by Bragaadeesh
        
        
        
        Published on 2010-06-15T06:12:32Z
        Indexed on 
            2010/06/15
            6:32 UTC
        
        
        Read the original article
        Hit count: 175
        
Hi,
Which of these two forms of Array Initialization is better in Ruby?
Method 1:
DAYS_IN_A_WEEK = (0..6).to_a
HOURS_IN_A_DAY = (0..23).to_a
@data = Array.new(DAYS_IN_A_WEEK.size).map!{ Array.new(HOURS_IN_A_DAY.size) }
DAYS_IN_A_WEEK.each do |day|
  HOURS_IN_A_DAY.each do |hour|
    @data[day][hour] = 'something'
  end
end
Method 2:
DAYS_IN_A_WEEK = (0..6).to_a
HOURS_IN_A_DAY = (0..23).to_a
@data = {}
DAYS_IN_A_WEEK.each do |day|
  HOURS_IN_A_DAY.each do |hour|
    @data[day] ||= {}
    @data[day][hour] = 'something'
  end
end
The difference between the first method and the second method is that the second one does not allocate memory initially. I feel the second one is a bit inferior when it comes to performance due to the numerous amount of Array copies that has to happen.
However, it is not straight forward in Ruby to find what is happening. So, if someone can explain me which is better, it would be really great!
Thanks
© Stack Overflow or respective owner