I needed to get the minimum and maximum date values from a query using the Sequel ORM in Ruby from my database. Sequel has a range
method that returns a Range value. I'm having it return values from a timestamp field, so they're coming back as a range of Time objects.
In order to split it into two variables using parallel assignment, I figured this was about as concise and succinct as I could get:
template_min_datestamp, template_max_datestamp = [Template.range(:created_at)].map{ |r| [r.min, r.max] }
I considered using:
template_min_datestamp, template_max_datestamp = Template.min(:created_at), Template.max(:created_at)
but that'd cause two hits to the database, which just makes my eye twitch.
Simplifying it for the innocent, and factoring out the ORM calls, it'd look something like this in regular Ruby:
t1 = Time.parse('Jan 1, 2013 12:00:00 -700')
t2 = Time.parse('Jan 31, 2013 12:00:00 -700')
template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] }
It seems like there'd be a more direct way to break apart a range into two elements on one line using parallel assignment, but it's escaping me right now.
Anyone got some enlightenment to share?
template_min_datestamp, template_max_datestamp = [t1..t2].map{ |r| [r.min, r.max] }[0]
this works, but I'm not sure if it is what you want. \$\endgroup\$ – Yuriy Golobokov Mar 23 '13 at 5:07map
+first
works, it seems a very non-declarative workaround of the abstraction as/into/chain/... \$\endgroup\$ – tokland Mar 25 '13 at 9:47