将带有空格的字符串转换为URL

Ste*_*eve 11 ruby url-encoding yql

我正在使用ruby和googles反向地理编码yql表来理想地自动化我的一些搜索查询.我遇到的问题是将查询转换为合法的网址格式.问题是我正在使用的编码是返回非法网址.我正在运行的查询如下

query="select * from google.geocoding where q='40.714224,-73.961452'" 
pQuery= CGI::escape(query)
Run Code Online (Sandbox Code Playgroud)

处理后的查询的最终输出如下所示

http://query.yahooapis.com/v1/public/yql?q=select+%2A+from+google.geocoding+where+q%3D%2740.3714224%2C--73.961452%27+format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=
Run Code Online (Sandbox Code Playgroud)

唉,网址是非法的.在YQL控制台中检查查询的内容时,我得到以下内容

http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.geocoding%20where%20q%3D%2240.714224%2C-73.961452%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=
Run Code Online (Sandbox Code Playgroud)

正如你可以看到:),编码完全错误.我想知道有谁知道如何生成正确的网址.

Jör*_*tag 22

如果要转义URI,则应使用URI::escape:

require 'uri'

URI.escape("select * from google.geocoding where q='40.714224,-73.961452'")
# => "select%20*%20from%20google.geocoding%20where%20q='40.714224,-73.961452'"
Run Code Online (Sandbox Code Playgroud)