From: Robert Klemme Date: 2009-12-11T02:08:22+09:00 Subject: Re: Fill gaps in Array of Hashes 2009/12/10 Aldric Giacomoni : > Joao Silva wrote: >> I have the following object as a result from MySQL: >> >> [{:positive=>"0", :neutral=>"2", :total=>"5", :date=>"2009-12-01", >> :negative=>"3"}, {:positive=>"3", :neutral=>"3", :total=>"7", >> :date=>"2009-12-08", :negative=>"1"}, {:positive=>"1", :neutral=>"1", >> :total=>"3", :date=>"2009-12-09", :negative=>"1"}] >> >> I want to fill gaps (for example from 2009-11-19 till 2010-10-01) with >> {:positive=>"0", :neutral=>"0", :total=>"0", :date=>"HEREDATE", >> :negative=>"1" - how i can do this in ruby? In MySQL it's impossible to >> do :-(. > > Well, the dumb, brute-force way to do it would be something like this, I > guess: > > # Assuming your array is called 'array' > require 'rubygems' > require 'activesupport' # What? I'm lazy. to_date is damn handy. > > ("2009-11-19".to_date.."2010-10-01".to_date).each do |date| >  exists = array.find { |x| x[:date] == date.to_s } >  next if exists # If the date is found in the array, next date please. >  array << { :positive => "0", :neutral => "0", :total => "0", :date => > date, >             :negative => "1" } > end Here's a different approach - not with dates though. # just an example def next_val(x) x + 2 end with_gaps = Array.new(10) { rand(40) * 2 } puts "before" p with_gaps with_gaps.sort.each_cons 2 do |a,b| next if a == b x = a while (x = next_val(x)) != b with_gaps << x end end puts "after" p with_gaps.sort # automated check with_gaps.sort.each_cons 2 do |a,b| raise("Wrong distance %s" % [a,b].inspect) unless a == b || next_val(a) == b end Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/