Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

ruby - Add parameter to url

I have a url (e.g. http://www.youtube.com/watch?v=og9B3BEnBHo) and I'd like to add a parameter to it (wmode=opaque) so that its:

http://www.youtube.com/watch?v=og9B3BEnBHo&wmode=opaque

Can anyone tell me which function to use to make this work?

question from:https://stackoverflow.com/questions/7785793/add-parameter-to-url

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
require 'uri'

uri =  URI.parse("http://www.youtube.com/watch?v=og9B3BEnBHo")
uri.query = [uri.query, "wmode=opaque"].compact.join('&') 
puts uri.to_s

#edit Since 1.9.2 there are methods added to the URI module

uri =  URI.parse("http://www.youtube.com/watch?v=og9B3BEnBHo")
new_query_ar = URI.decode_www_form(String(uri.query)) << ["wmode", "opaque"]
uri.query = URI.encode_www_form(new_query_ar)
puts uri.to_s

(The call to String ensures that this also works in the case when the original URI does not have a query string)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...