Moh*_*awy 65 ruby ruby-on-rails ruby-on-rails-3
鉴于字符串:
"Hello there world"
Run Code Online (Sandbox Code Playgroud)
如何创建URL编码的字符串,如下所示:
"Hello%20there%20world"
Run Code Online (Sandbox Code Playgroud)
如果字符串也有其他符号,我也想知道该怎么做,比如:
"hello there: world, how are you"
Run Code Online (Sandbox Code Playgroud)
最简单的方法是什么?我打算解析,然后为此构建一些代码.
Ari*_*iao 117
require 'cgi'
CGI.escape("Hello world")
#=> "Hello+world"
Run Code Online (Sandbox Code Playgroud)
the*_*Man 17
Ruby的URI对此非常有用.您可以以编程方式构建整个URL并使用该类添加查询参数,它将为您处理编码:
require 'uri'
uri = URI.parse('http://foo.com')
uri.query = URI.encode_www_form(
's' => "Hello there world"
)
uri.to_s # => "http://foo.com?s=Hello+there+world"
Run Code Online (Sandbox Code Playgroud)
这些例子非常有用:
URI.encode_www_form([["q", "ruby"], ["lang", "en"]])
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => "ruby", "lang" => "en")
#=> "q=ruby&lang=en"
URI.encode_www_form("q" => ["ruby", "perl"], "lang" => "en")
#=> "q=ruby&q=perl&lang=en"
URI.encode_www_form([["q", "ruby"], ["q", "perl"], ["lang", "en"]])
#=> "q=ruby&q=perl&lang=en"
Run Code Online (Sandbox Code Playgroud)
这些链接也可能有用:
小智 13
如果有人有兴趣,最新的方法就是在ERB中做:
<%= u "Hello World !" %>
Run Code Online (Sandbox Code Playgroud)
这将呈现:
您好%20World%20%21
你是url_encode的缩写
你可以在这里找到文档