Leo Burt
Leo Burt

Reputation: 109

Round date in the Array and delete before item

I have an array of DateTime objects like:

a = [
 [Tue, 05 Mar 2013],
 [Tue, 12 Mar 2013],
 [Tue, 19 Mar 2013],
 [Tue, 26 Mar 2013],
 [Tue, 02 Apr 2013],
 [Tue, 09 Apr 2013]
]

where a[0] is a Date object. I need to search for a specific date, like:

a.index('Tue, 06 Mar 2013'.to_date)

to find its index and delete everything before (and in another case after) this item. I need to search by any date, like in the example above, I'm searching by Tue, 05 Mar 2013, so it should be rounded to the nearest value: Tue, 05 Mar 2013. How could it be done in a Ruby way?

Upvotes: 0

Views: 130

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

Here is the way :

I need to search it for specific date.

require 'date'

a = [
 ['Tue, 05 Mar 2013'],
 ['Tue, 12 Mar 2013'],
 ['Tue, 19 Mar 2013'],
 ['Tue, 26 Mar 2013'],
 ['Tue, 02 Apr 2013'],
 ['Tue, 09 Apr 2013']
]

nwar = a.flatten.map{|d| Date.parse(d)}
# point free style is - a.flatten.map(&Date.method(:parse))
srchdt = Date.parse('Tue, 06 Mar 2013')
p nwar.index(srchdt) # => nil
srchdt = Date.parse('Tue, 26 Mar 2013')
p nwar.index(srchdt) # => 3

After we have index of the item, I need to delete everything before (another case is to delete after) this item.

ind = nwar.index(srchdt) # => 3
nwar.shift(ind)
p nwar.map(&:to_s) # => ["2013-03-26", "2013-04-02", "2013-04-09"]

Upvotes: 0

fotanus
fotanus

Reputation: 20116

Instead of using dates, should be easier to use timestamps:

'Tue, 06 Mar 2013'.to_time.to_i
 => 1362528000 

Higher the value, more in the future this date is.

If you are not inserting items in your list frequently, every time you insert a new item, sort it. When you find the index for the date , remove all other items. For example:

# Your dates list converted to timestamps
> times 
 => [1362441600, 1363046400, 1363651200, 1364256000, 1364860800, 1365465600] 
# Find the timestamp equal or greater than the given date
> correct_index_val = times.find{|x| x <= 'Tue, 27 Mar 2013'.to_time.to_i}
 => 1362441600 # this is actually the position for 26 Mar
# Position of the value equal or greater than the given date
> times.index(correct_index_val)
 => 3
# cutting the array in that point
> times[idx..-1]
 => [1364256000, 1364860800, 1365465600] 

Upvotes: 1

Related Questions