Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove everything after first whitespace or certain number of characters?

Tags:

regex

ruby

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

2008-10-09 20:30:40

I only want the day portion:

2008-10-09

I'm looking for a gsub line that will strip everything after a set number of characters or the first whitespace.

like image 517
Ryan Teuscher Avatar asked Dec 09 '25 20:12

Ryan Teuscher


2 Answers

I prefer to use as simple a solution as I can. Using gsub is needlessly complex. Either of these will do it:

str = '2008-10-09 20:30:40'
str[/(\S+)/, 1] #=> "2008-10-09"
str[0, 10] #=> "2008-10-09"
like image 118
the Tin Man Avatar answered Dec 11 '25 13:12

the Tin Man


Literal solution:

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

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

date[0, 10]

Better solution: Treat it as a DateTime object - then you can format it as you wish:

date = DateTime.now
date.strftime("%m-%d-%Y") # America
date.strftime("%d-%m-%Y") # Europe
like image 40
Amadan Avatar answered Dec 11 '25 12:12

Amadan