I am trying to parse through a file and replace some days/dates.
For example,
I want to change
In a post on the band's blog last night (06.05.12)
to
In a post on the band's blog sunday night
I am trying to use gsub! to do so.
r.gsub!(/\blast night \(([0-3][0-9]\.[0-1][0-9]\.[0-9][0-9])\)/ei,Date.strptime('\1',"%d.%m.%y").strftime("%A").to_s + ' night')
always says invalid date, but
r.gsub!(/\blast night \(([0-3][0-9]\.[0-1][0-9]\.[0-9][0-9])\)/ei,'\1')
shows the right date as 06.05.12
and
mydate = '06.05.12'
r.gsub!(/\blast night \(([0-3][0-9]\.[0-1][0-9]\.[0-9][0-9])\)/ei,Date.strptime(mydate,"%d.%m.%y").strftime("%A").to_s + ' night')
gives me the appropriate response. Why doesn’t replacing mydate with \1 work when using Date.strptime? Any suggestions on how to go around this?
You seem to try to reference the match group in your date function. This doesn’t work though. The syntax is only available if you replace simple strings. The
gsubfunction replaces all references in the passed string, but only when it is actually passed to the function. Your code is equivalent toThe “replacement” thus can’t work as
'\1'is not a valid date. The gsub replacement would only applied to the string returned by yourstrftimefunction. However, you can use the magic match variables which are set the the matching groups automatically:Notice that I wrote
$1instead of\1in thestrptimearguments