Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove trailing "?" from a string

I have this url:

http://localhost:3000/blog/posts?locale=en

I have a helper to remove ?locale=en of url:

def url_without_locale_params(url)
  uri = URI url
  params = Rack::Utils.parse_query uri.query
  params.delete 'locale'
  uri.query = params.to_param
  uri.to_s
end

With this helper I get this url http://localhost:3000/blog/posts?. I would like to delete the trailing ?.

The result should be http://localhost:3000/blog/posts.

like image 379
hyperrjas Avatar asked Apr 03 '13 10:04

hyperrjas


2 Answers

Use #gsub:

uri = "http://localhost:3000/blog/posts?locale=en"
uri.gsub(/\?.*/, '')
  #=> "http://localhost:3000/blog/posts"
like image 113
Jon Cairns Avatar answered Oct 03 '22 11:10

Jon Cairns


String#chomp is a possibility.

1.9.3p392 :002 > "foobar?".chomp("?")
 => "foobar" 

The final method will be

def url_without_locale_params(url)
  uri = URI url
  params = Rack::Utils.parse_query uri.query
  params.delete 'locale'
  uri.query = params.to_param
  uri.to_s.chomp("?")
end
like image 23
Simone Carletti Avatar answered Oct 03 '22 12:10

Simone Carletti