如何使用 Ruby 或 Rails 从 URL 中提取 URL 参数? [英] How to extract URL parameters from a URL with Ruby or Rails?
本文介绍了如何使用 Ruby 或 Rails 从 URL 中提取 URL 参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一些网址,比如
http://www.example.com/something?param1=value1¶m2=value2¶m3=value3
我想从这些 URL 中提取参数并将它们放入哈希中.显然,我可以使用正则表达式,但我只是想知道使用 Ruby 或 Rails 是否有更简单的方法来做到这一点.我在 Ruby 模块 URI
中没有找到任何东西,但也许我错过了一些东西.
and I would like to extract the parameters from these URLs and get them in a Hash. Obviously, I could use regular expressions, but I was just wondering if there was easier ways to do that with Ruby or Rails. I haven't found anything in the Ruby module URI
but perhaps I missed something.
事实上,我需要一种方法来做到这一点:
In fact, I need a method that would do that:
extract_parameters_from_url("http://www.example.com/something?param1=value1¶m2=value2¶m3=value3")
#=> {:param1 => 'value1', :param2 => 'value2', :param3 => 'value3'}
你有什么建议吗?
推荐答案
我认为您想将任何给定的 URL 字符串转换为 HASH?
I think you want to turn any given URL string into a HASH?
你可以试试http://www.ruby-doc.org/stdlib/libdoc/cgi/rdoc/classes/CGI.html#M000075
require 'cgi'
CGI::parse('param1=value1¶m2=value2¶m3=value3')
返回
{"param1"=>["value1"], "param2"=>["value2"], "param3"=>["value3"]}
这篇关于如何使用 Ruby 或 Rails 从 URL 中提取 URL 参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文