user1883793 user1883793 - 1 year ago 30
Ruby Question

how to prepend each letter with a symbol using Regex

I have a string time format like this:

d-m-Y H:i
. I want to format it like this:
%d-%m-%Y %H:%i

How do I prepend each letter with
using regular expressions?


This is pretty basic using String#gsub:

str = "d-m-Y H:i"
str.gsub(/[a-z]/i, '%\0')
# => "%d-%m-%Y %H:%i"

In the replacement string '%\0', \0 represents the entire match, which in this case is the matched letter, so this says, "Replace each letter with a % followed by the letter."