In the discussion “Escaping a backslash in a regex,” huynhthai824 asked how to replace a string containing a forward slash / in a regex. They provided code that was causing a syntax error due to the unescaped / in the regex pattern.
Heliosurge suggested removing the slashes and testing, and also pointed out a missing quote in the original code. However, this approach was not necessary.
supermathie provided the correct solution, which was to escape the / with a backslash \. They demonstrated this with an example in pry:
'T8/2024'.gsub(/T8\/2024/, 'T9/2024')
huynhthai824 implemented this solution and confirmed that it worked, updating their original code to:
Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
topic.title.gsub!(/T8\/2024/,"T9/2024")
topic.fancy_title.gsub!(/T8\/2024/,"T9/2024")
topic.slug.gsub!(/T8\/2024/,"T9/2024")
puts topic.title
begin
topic.save!
rescue
puts "oops, something broke."
end
end
Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
topic.title.gsub!(/T8/2024/,"T9/2024")
topic.fancy_title.gsub!(/T8/2024/,"T9/2024")
topic.slug.gsub!(/T8/2024/,"T9/2024")
puts topic.title
begin
topic.save!
rescue
puts "oops, something broke."
end
end
Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
topic.title.gsub!("T8/2024","T9/2024")
topic.fancy_title.gsub!(/T8/2024","T9/2024")
topic.slug.gsub!("T8/2024","T9/2024")
puts topic.title
begin
topic.save!
rescue
puts "oops, something broke."
end
end
Topic.where("title LIKE '%T8/2024%'").find_each do |topic|
topic.title.gsub!(/T8\/2024/,"T9/2024")
topic.fancy_title.gsub!(/T8\/2024/,"T9/2024")
topic.slug.gsub!(/T8\/2024/,"T9/2024")
puts topic.title
begin
topic.save!
rescue
puts "oops, something broke."
end
end