Ryan Teuscher
Ryan Teuscher

Reputation: 133

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

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.

Upvotes: 3

Views: 2366

Answers (4)

Amadan
Amadan

Reputation: 198324

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

Upvotes: 2

the Tin Man
the Tin Man

Reputation: 160551

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"

Upvotes: 6

DigitalRoss
DigitalRoss

Reputation: 146073

'2008-10-09 20:30:40'.split[0]

Upvotes: 0

sawa
sawa

Reputation: 168101

If the format is consistantly like that,

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

Upvotes: 1

Related Questions