views:

826

answers:

4

In Ruby, what's the best way to convert a string of the format: "{ 2009, 4, 15 }" to a Date?

+1  A: 

Best I could do was:

Date.new(*"{ 2009, 04, 15 }".delete('{').chop.split(",").map(&:to_i))

Is there a more elegant way?

jjnevis
+1  A: 

Another way:

s = "{ 2009, 4, 15 }"
d = Date.parse( s.gsub(/, */, '-') )
FM
+7  A: 

You could also use Date.strptime:

Date.strptime("{ 2009, 4, 15 }", "{ %Y, %m, %d }")
robinst
cool :). this is it
fl00r
very nice and very clear - thanks!
jjnevis
A: 
def parse_date(date)
  Date.parse date.gsub(/[{}\s]/, "").gsub(",", ".")
end

date = parse_date("{ 2009, 4, 15 }")
date.day
#=> 15
date.month
#=> 4
date.year
#=> 2009
fl00r