Ответ 1
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"
С учетом строки:
"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"
Эти ссылки также могут быть полезны:
Если кому-то интересно, самый новый способ сделать это в ERB:
<%= u "Hello World !" %>
Это сделает:
Привет %20World %20% 21
u не подходит для url_encode
Здесь вы можете найти документы