Entisburg Entisburg - 6 months ago 29
Ruby Question

What does dup.sub! in Ruby, such as follows?

I'm trying to figure out what

s.dup.sub!
is doing in the following function. I assume
s
is a string. Sorry if this question is not appropriate.

def authenticated_url(s)
s.dup.sub!(%r{^(https://)(.*)}, '\1' + access_token + '@\2')
end

Answer

Two methods are being run here: dup and sub!.

From inference, s is a string being passed in. It's being copied subject to the rules of dup (which does not mutate the argument being passed in), then it is being mutated in place, embedding whatever value access_token holds between https:// and whatever's after that.

As pointed out in the comments, a more straightforward approach would have been to use s.sub instead, since sub (without the !) will return a new string without the need to copy, and will at least guarantee that a string is brought back if no substitutions are made.