Shpigford Shpigford - 3 months ago 11
Ruby Question

Append string if not already present

I have strings of time (how poetic) from a third party and some have the timezone while others don't. What I'd like to do append a timezone if one isn't present.

Here are examples of strings with timezones...

5:21 AM MT
10:01 PM MT
8:41 PM MT


But sometimes that
MT
is missing for whatever reason.

So, what I need to do is append
MT
after
AM
or
PM
if it's missing.

(Note, I can't just check for
MT
. It could be any timezone. The primary goal here is to be able to append any timezone I choose after
AM
or
PM
).

Answer

If the AM/PM indicator is always there I would probably just check to see what the end of the string is and then append if necessary:

if string.match(/\ (A|P)M$/)
  string << " #{timezone}"
end

If not (ie: 24 time), you might be better off parsing the strings through a Date or Time parser and appending the timezone that way once the string is cast to the appropriate object.

Comments