"Hello there world"
我怎么可以创建一个URL编码的字符串是这样的:
"Hello%20there%20world"
我也想知道什么如果字符串也有其他符号,例如:
"hello there: world, how are you"
这样做最简单的方法是什么?我打算解析并为此构建一些代码。
"Hello there world"
我怎么可以创建一个URL编码的字符串是这样的:
"Hello%20there%20world"
我也想知道什么如果字符串也有其他符号,例如:
"hello there: world, how are you"
这样做最简单的方法是什么?我打算解析并为此构建一些代码。
require 'uri'
URI.encode("Hello there world")
#=> "Hello%20there%20world"
URI.encode("hello there: world, how are you")
#=> "hello%20there:%20world,%20how%20are%20you"
URI.decode("Hello%20there%20world")
#=> "Hello there world"
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"
的例子是有用的:
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"
这些链接也可能是有用:
我怎么能嵌入要求 'URI'进入html.erb?或者我必须把它放入控制器? –
任何时候当需要更多的微不足道的逻辑时,正确的做法是在控制器中完成所有“computin”。 –
很酷。我们什么时候应该使用助手?如果我们做了计算,可以在帮助程序的许多地方使用,并且包含在控制器中。有关系吗? –
如果你也想编码点:'URI.encode( 'api.example.com',/ \ W /)' – Dennis