views:

426

answers:

4

How can I, very simply construct a hash in ruby using something simple like "times"

I have a @date (ie = Date.today) and then a number of days... say 5

5.times { |i| @date_range[:day] = (@date+i).strftime("%Y-%m-%d") }

I know there's got to be something super simple that's missing.

Thanks...

+1  A: 

This seems to work...

(1..10).each { |i| @date_range[i] = (@date+i).strftime("%Y-%m-%d") }
holden
+6  A: 

Date objects are also Comparable, so you could construct a Range:

@range = @date..(@date + 10)

You can iterate over it easily and output the results. If you want to access a particular date numerically, you can do:

@date_range = (@date..(@date + 10)).to_a
@date_range[1]

Or if you really need to format the dates beforehand, as in your example:

@date_range = (@date..(@date + 10)).map { |date| date.strftime("%Y-%m-%d") }
@date_range[1]

The final line would be equivalent in use to your @date_range[1] (equal to tomorrow / @date + 1), even though it is actually an Array rather than a Hash. A Hash with sequential numeric keys doesn't make a lot of sense: you get those for free with an Array and, as a bonus, the order of the values is preserved. In my opinion, using Ranges to start with slightly clarifies the intent, but it's not a spectacular difference.

molf
A: 

you can use collect to create an array in one line, but I'm not sure where your hash comes in...

@date_range = 5.times.collect { |i| (@date+i).strftime("%Y-%m-%d") }
glenn jackman
A: 

You want a hash that contains today's date plus the hash key?

today = Date.today
days = Hash.new { |h,k| h[k] = (today + k).strftime( '%Y-%m-%d' ) }

This has the advantage of not being limited to a few days. It'll work for any key. Plus, the calculation happens only once per key and as needed.

toholio