我在字符串中有一个URL.添加一些参数的最简洁方法是什么?
例如
base = 'http://example.com' uri1 = some_magical_method(base,:p1 => 'v1') # => http://example.com/?p1=v1 uri2 = some_magical_method(uri1,:p2 => 'v2') # => http://example.com/?p1=v1&p2=v2 uri3 = some_magical_method(uri2,:p3 => nil) # => http://example.com/?p1=v1&p2=v2
1)在Ruby?
2)在Rails中?
解决方法
在Rails中,ActiveSupport可用,最简单的方法是构造一个哈希,然后在其上调用#to_query.
>> params = {} >> params[:foo] = "bar" >> params[:baz] = "bang" >> params.to_query => "baz=bang&foo=bar"
在纯Ruby中,同样适用,但您需要自己编写编码器:
require 'cgi' def to_query(hsh) hsh.map {|k,v| "#{k}=#{CGI::escape v}" }.join("&") end params = {} params[:foo] = "bar" params[:baz] = "bang" to_query params => "baz=bang&foo=bar"