Severin
Severin

Reputation: 8588

Partial string replace with gsub

I have an array of different image urls where I need to replace "/s_" with "/xl_". Ive tried a number of different ways, but non of them seems to work as I expect them to. Here is my latest version:

available_images.each do |img|
    img.gsub(/.*(\/s_).*\.jpg/, "\/xl_")
end

available_images is the array holding a number of strings (which of course match the provided regex: .*(/s_).*.jpg ). Any thoughts on how that can be fixed?

Thanks in advance!

Upvotes: 2

Views: 691

Answers (1)

tessi
tessi

Reputation: 13574

A gsub! (! because you do a each and not a map) with a simple string (instead of a regex) should work:

"path/to/s_image.jpg".gsub '/s_', '/xl_'
# => "path/to/xl_image.jpg"

Update

As pointed out in the comments, the solution might result in unexpected behavior if the path contains multiple occurrences of '/s_'.

"path/s_thing/s_image.jpg".gsub '/s_', '/xl_'
#=> "path/xl_thing/xl_image.jpg"
          ▲        ▲

Borodin posted a nice, short regex substitution, which works in that case:

"path/s_thing/s_image.jpg".sub %r|/s_(?!.*/)|, '/xl_'
#=> "path/s_thing/xl_image.jpg"
          △        ▲

It only replaces the last occurrence of '/s_'.

Upvotes: 1

Related Questions