Ruby url encoding string



  • 3 Answer(s)

    Ruby url encoding string: 

    require 'uri'
    str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".force_encoding('ASCII-8BIT')
    puts URI::encode(str)
    

    Answered on January 12, 2019.
    Add Comment

    Follow this command:

    str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
    require 'cgi'
    CGI.escape(str)
    # => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"
    

    Answered on January 12, 2019.
    Add Comment

    Using ERB::Util.url_encode or CGI.escape. They primary difference between them is their handling of spaces:

    >> ERB::Util.url_encode("foo/bar? baz&")
    => "foo%2Fbar%3F%20baz%26"
    >> CGI.escape("foo/bar? baz&")
    => "foo%2Fbar%3F+baz%26"
    

    The CGI.escape  gives you an application/x-www-form-urlencoded string requires spaces be escaped to +, whereas ERB::Util.url_encode. which requires them to be encoded as %20.

    Answered on January 12, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.