How to delete everything after the first space or a certain number of characters?

I have a date string that I need to simplify in Ruby:

2008-10-09 20:30:40

I need only part of the day:

2008-10-09

I am looking for a gsub string that will split everything after a given number of characters or the first space.

+3
source share
4 answers

I prefer to use the simplest solution possible. Use gsubis unnecessarily complicated. Any of them will do this:

str = '2008-10-09 20:30:40'
str[/(\S+)/, 1] #=> "2008-10-09"
str[0, 10] #=> "2008-10-09"
+6
source

Literary solution:

date.gsub(/(.{10}).*/, '\1')

date.gsub(/\s.*/, '')

date[0, 10]

Best solution: consider it as a DateTime object - then you can format it as you like:

date = DateTime.now
date.strftime("%m-%d-%Y") # America
date.strftime("%d-%m-%Y") # Europe
+2
source

If the format is the same

'2008-10-09 20:30:40'[/[-\d]+/] # => "2008-10-19"
+1
source
'2008-10-09 20:30:40'.split[0]
0
source

All Articles