Damir Nurgaliev
Damir Nurgaliev

Reputation: 351

How to correctly swap some characters in string

I have a string that represents a date:

"12.27.1995"

I need to swap the month and the day to get:

"27.12.1995"

I did:

date = "12.27.1995"

month = date[0]+date[1]
day = date[3]+date[4]

date[0] = day[0]
date[1] = day[1]
date[3] = month[0]
date[4] = month[1]

It works good, but looks to bad for me. Is it possible to make it more reliable using less code?

Upvotes: 2

Views: 265

Answers (4)

Eric Duminil
Eric Duminil

Reputation: 54223

Since your string represents a date, you might want to use a Date object, with strptime to parse the original string and strftime to output it in the desired format:

require 'date'

date = Date.strptime("12.27.1995", "%m.%d.%Y")
puts date.strftime("%d.%m.%Y")
# 27.12.1995

Upvotes: 7

Sagar Pandya
Sagar Pandya

Reputation: 9497

Not elegant, but a way using regex captures:

/(\d{1,2})\.(\d{1,2})\.(\d{4})/.match "12.27.1995"
[$2, $1, $3].join('.') #=> "27.12.1995"

Upvotes: 1

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

While the answer by @sawa is perfectly valid and should be used here, I would show some technic which is wrong and should not be used here, but might be helpful for anybody to swap two fixed parts of the string:

"12.27.1995".tap { |s| s[0..1], s[3..4] = s[3..4], s[0..1] }
#⇒ "27.12.1995"

Upvotes: 1

sawa
sawa

Reputation: 168071

Yes. Perhaps like this:

date = "12.27.1995"
m, d, y = date.split(".")
date = [d, m, y].join(".")

Upvotes: 6

Related Questions