Dedy Puji
Dedy Puji

Reputation: 625

replace string url in certain path

I have link to image

link = "https://ecs7.sandal.net/img/cache/500-square/product-10/2019/6/16/719184/719184_de07958e-9e6b-491a-ae61-2291220be643_1080_1080.jpg"

the path after /img/cache which is 500-square is the size of the image.

the link is dynamic. but the size is alway after the cache/ path.

and the rest of link after the size path is product folder, so it can be ignored.

500-square is to small for image i want. so i have to change to 900 or some other size.

so the link will be like this below

https://ecs7.sandal.net/img/cache/900/product-10/2019/6/16/719184/719184_de07958e-9e6b-491a-ae61-2291220be643_1080_1080.jpg

how to replace 500-square to 900 using ruby string ?

thanks

Upvotes: 1

Views: 238

Answers (2)

Todd A. Jacobs
Todd A. Jacobs

Reputation: 84343

Replace Whole Substring

There are many ways to do this, depending on how much your data varies and how well-structured it is. However, if you know that your link variable will always want to replace the substring 500-square then you can simply use String#sub to replace the value. For example:

# replace entire substring
link.sub '500-square', '900'
#=> "https://ecs7.sandal.net/img/cache/900/product-10/2019/6/16/719184/719184_de07958e-9e6b-491a-ae61-2291220be643_1080_1080.jpg"

If you don't want to mess with regular expressions, this is the way to go. Additionally, you can still anchor the expression to a portion of the URI path if there might be other potential matches. For example:

# anchor expression with slashes
link.sub '/500-square/', '/900/'
#=> "https://ecs7.sandal.net/img/cache/900/product-10/2019/6/16/719184/719184_de07958e-9e6b-491a-ae61-2291220be643_1080_1080.jpg"

If you need to key off something else, such as location within the URL or other attribute, then you may need a more complex solution. The code above will certainly address the use case posted, though.

Upvotes: 2

Sara Fuerst
Sara Fuerst

Reputation: 6068

You can split the string on the "/"

link_list = link.split("/") 

Then you can replace "500-square"

link_list[link_list.index("500-square")] = "900" 

Then join it together with the "/"

link = link_list.join("/") 

Upvotes: 0

Related Questions