I have a string like this (YYYYMMDD):
20120225
And I want to have a string like this (MM/DD/YYYY):
02/25/
Just for fun how about:
'20120225'.unpack('A4A2A2').rotate.join('/')
Parsing it then formatting it is the best solution:
Date.parse("20120225").strftime("%m/%d/%Y") #=> "02/25/2012"
It's possible with regular expressions:
s1 = '20120225'
s2 = "$2/$3/$1" if s1 =~ /(\d{4})(\d{2})(\d{2})/
Or if you're sure of the format of your string and have performance issues, I think the best solution is
s2 = s1[4..5] + '/' + s1[6..7] + '/' + s1[0..3]
But if you have no performance needs, I think the solution of Andrew Marshall is better because it checks the date validity.
strptime parses the string representation of date with the specified template and creates a date object.
Date.strptime('20120225', '%Y%m%d').strftime("%m/%d/%Y") #=> "02/25/2012"