Michael Lee Michael Lee -5 years ago 127
Ruby Question

Create nested array from existing array

I'm tying to create an array of dates, based on a user input of the date. The goal is to take the date input by the user and generate 16 date pairs (in sequential order).

I was able to figure how to generate the start dates and put them in an array, but I can't quite figure out how to take that array and further break them up in to sub-arrays (the date pairs).

Here's the code I used to generate the start dates:

@date_pairs = (@input_date-105..@input_date).step(7).to_a.reverse

I tried to create a sub-array in the following way:

@date_pairs = (@input_date-105..@input_date).step(7).to_a.reverse.each { |x| Array.new(x, x-6)}

However I get the following error: no implicit conversion of Date into Integer

Here's an example of what i'm hoping to get:

@input_date = 6/15/2016
@date_pairs = [[6/15/2016, 6/9/2016], [6/8/2016, 6/2/2016], [6/1/2016, 5/24/2016].....]

The goal is to be able to iterate over the @date_pairs, accessing each value within the sub-array.

I plan to use this concept to create other types of date pairs (ie, date pairs separated by months, years, etc)


Answer Source

It's hard for me to be sure without knowing what your @input_date looks like, but I think you're really close. You're probably getting that error because your x is an instance of DateTime and you're trying to subtract 6 (an Integer) from it. Maybe try subtracting 6.days instead, like so:

@date_pairs = (@input_date-105..@input_date).step(7).to_a.reverse.map { |x| [x, x-6.days] }

Also note that Array.new(5, 6) produces [6, 6, 6, 6, 6] -- probably not what you want here.

Hope that helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download