简体   繁体   中英

one line hash creation in ruby

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...

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 Range s to start with slightly clarifies the intent, but it's not a spectacular difference.

这似乎有效...

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

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.

您可以使用collect在一行中创建一个数组,但是我不确定您的哈希值在哪里...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM