Ruby, How to add a param to an URL that you don't know if it has any other param already

前端 未结 3 1737
忘掉有多难
忘掉有多难 2021-02-07 10:54

I have to add a new param to an indeterminate URL, let\'s say param=value.

In case the actual URL has already params like this

http://url.co         


        
3条回答
  •  一向
    一向 (楼主)
    2021-02-07 11:18

    Well, you may also not know if this parameter already exists in url. If you want to replace it with new value in this case, you can do this:

    url = 'http://example.com?exists=0&other=3'
    params = {'exists' => 1, "not_exists" => 2}
    uri = URI.parse url
    uri.query = URI.encode_www_form(URI.decode_www_form(uri.query || '').to_h.merge(params))
    uri.to_s
    

提交回复
热议问题