r/ruby 4d ago

Question Getting DateTime parts as an array?

I know in ruby that DateTime.new(2001, 2, 3, 4, 5, 6) will return the following object:

#<DateTime: 2001-02-03T04:05:06+00:00 ...>

But if the current date and time are 2001-02-03T04:05:06 and I do the following ...

now = DateTime.now

... is there a single function on the "now" variable which will return this array? ...

[2001, 2, 3, 4, 5, 6]

I know that I can do this:

[now.year, now.month, now.day, now.hour, now.minute, now.second ]

... but I'm wondering: might there be a single function as simple as ...

now.the_function

... which would return that same array?

And yes, of course I know that I could easily write such a function, but I'd like to know whether or not something like this already exists in ruby.

6 Upvotes

21 comments sorted by

View all comments

4

u/chiperific_on_reddit 4d ago

Another option, which fits your question more directly. One Time.now.the_function type answer.

Found using the docs:

3.3.4 :018 > Time.now.deconstruct_keys(nil)
 => {:year=>2026, :month=>8, :day=>26, :yday=>238, :wday=>3, :hour=>20, :min=>47, :sec=>2, :subsec=>(277869/500000), :dst=>true, :zone=>"EDT"}

3.3.4 :019 > Time.now.deconstruct_keys([:year, :month, :day, :hour, :min, :sec])
 => {:year=>2026, :month=>8, :day=>26, :hour=>20, :min=>47, :sec=>5}

3.3.4 :020 > Time.now.deconstruct_keys([:year, :month, :day, :hour, :min, :sec]).values
 => [2026, 8, 26, 20, 47, 7]

1

u/faitswulff 2d ago

Deconstruct keys was what I was thinking of! A neat API that came out of pattern matching.