1

In ruby, I'm trying to replace the below url's bolded portion with new numbers:

/ShowForum-g1-i12105-o20-TripAdvisor_Support.html

How would I target and replace the -o20- with -o30- or -o40- or -o1200- while leaving the rest of the url intact? The urls could be anything, but I'd like to be able to find this exact pattern of -o20- and replace it with whatever number I want.

Thank you in advance.

Horse Voice
  • 8,138
  • 15
  • 69
  • 120

2 Answers2

1

Hope this will work.

url = "/ShowForum-g1-i12105-o20-TripAdvisor_Support.html"
url = url.gsub!(/-o20-/, "something_to_replace") 
puts "url is : #{url}"

Output:

sh-4.3$ ruby main.rb                                                                                                                                                 
url is : /ShowForum-g1-i12105something_to_replaceTripAdvisor_Support.html 
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
  • This gives me an error: syntax error, unexpected tIDENTIFIER, expecting ')' secondUrl.gsub(/­\-o20\­-/,'-o90-'­) ^ – Horse Voice Feb 22 '17 at 05:52
1
url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s

The snippet above will replace the number inplace with (itself + 10).

url = '/ShowForum-g1-i12105-o20-TripAdvisor_Support.html'

url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
#⇒ "30"
url
#⇒ "/ShowForum-g1-i12105-o30-TripAdvisor_Support.html"
url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
#⇒ "40"
url
#⇒ "/ShowForum-g1-i12105-o40-TripAdvisor_Support.html"

To replace with whatever number you want:

url[/(?<=-o)\d+(?=-)/] = "500"
url
#⇒ "/ShowForum-g1-i12105-o500-TripAdvisor_Support.html"

More info: String#[]=.

Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160
  • Mudsie, my reading of the question is that `"-o20"` is a given string, which of course simplifies the question considerably. – Cary Swoveland Feb 22 '17 at 08:00
  • @CarySwoveland I have read “I target and replace the -o20- with -o30- or -o40- or -o1200-” as the goal is to update the number, so I did my best to make it easy :) – Aleksei Matiushkin Feb 22 '17 at 08:18