Entisburg Entisburg - 9 months ago 58
Ruby Question

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

I'm trying to figure out what

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

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


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.