Will Ashley Will Ashley - 6 months ago 36
Ruby Question

Ruby regex capture groups in gsub

Say I want to switch each letter in a message with it's place in the reverse alphabet. Why can't I seem to use the captured group and do it in one gsub?

Perhaps someone could explain in general about using captured groups in gsub, can the back references be bare(no ' ')? Can I use #{\1}?

def decode(message)
a = ('a'..'z').to_a
z = a.reverse
message.gsub!(/([[:alpha:]])/, z[a.index('\1')])
end

decode("the quick brown fox")

Answer

Remember that arguments to methods are evaluated immediately and the result of that is passed in to the method. If you want to make the substitution adapt to the match:

message.gsub!(/([[:alpha:]])/) { |m| z[a.index($1)] }

That employs a block that gets evaluated for each match.

Comments