我正在尝试使用Ruby on Rails从哈希创建http参数,我尝试使用URI.encode_www_form(params)
,但这并没有正确生成参数。
以下是我的哈希
params['Name'.to_sym] = 'Nia Kun'
params['AddressLine1'.to_sym] = 'Address One'
params['City'.to_sym] = 'City Name'
This method converts space to +
,我想要的是convert space with %20
我收到"Name=Nia+Kun&AddressLine1=Address+One&City=City+Name"
,但我需要将这些空格转换为%20
答案 0 :(得分:3)
你可以这样做:
URI.encode_www_form(params).gsub("+", "%20")
如果那真的是你需要的。
另见When to encode space to plus (+) or %20?为什么会这样做。
答案 1 :(得分:1)
您可以编写自定义方法。像这样:
p = {x: 'some word', y: 'hello there'}
URI.encode p.to_a.map {|inner| inner.join('=') }.join('&')
# "x=some%20word&y=hello%20there"
所以基本上你将params展平为数组数组,然后将它们转换为url字符串,然后对其进行编码。
编辑:
最终解决方案将如下所示:
def encode_url(params)
URI.encode params.to_a.map {|inner| inner.join('=')}.join('&')
end
encode_url(my_params)
答案 2 :(得分:0)
您可以使用GSUB:
myString.gsub(" ", "%20")
引用doc:
此方法不会转换*, - ,。,0-9,A-Z,_,a-z,但会将SP(ASCII空间)转换为+并将其他转换为%XX。
答案 3 :(得分:0)
What you are looking for is URI::escape
.
URI::escape "this big string"
=> "this%20big%20string"
EDIT
Bringing it all together:
params
, rails is smart and knows about with_indifferent_access
. Strings and symbols will both work..
name = params['Name']# = 'Nia Kun'
address_one = params['AddressLine1']# = 'Address One'
city = params['City']# = 'City Name'
URI::encode "http://www.example.com?name=#{name}&address_one=#{address_one}&city=#{city}"
#=> "http://www.example.com?name=Nia%20Kun&address_one=Address%20One&city=City%20Name"