且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从 Rails 中的 URL 获取查询字符串

更新时间:2023-02-24 08:50:01

如果您在字符串中有一个 URL,那么使用 URI 和 CGI​​ 将其分开:

If you have a URL in a string then use URI and CGI to pull it apart:

url    = 'http://www.example.com?id=4&empid=6'
uri    = URI.parse(url)
params = CGI.parse(uri.query)
# params is now {"id"=>["4"], "empid"=>["6"]}

id     = params['id'].first
# id is now "4"

这些东西请使用标准库,不要尝试自己用正则表达式来做.

Please use the standard libraries for this stuff, don't try and do it yourself with regular expressions.

另见 Quv 对下面 Rack::Utils.parse_query 的评论.

Also see Quv's comment about Rack::Utils.parse_query below.

参考文献:

更新:这些天我可能会使用 Addressable::Uri 而不是标准库中的 URI :

Update: These days I'd probably be using Addressable::Uri instead of URI from the standard library:

url = Addressable::URI.parse('http://www.example.com?id=4&empid=6')
url.query_values                  # {"id"=>"4", "empid"=>"6"}
id    = url.query_values['id']    # "4"
empid = url.query_values['empid'] # "6"