Skip to content

Maintenance Ruby 3.4 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

URI.encode_www_form

(::Enumerable[[ ::_ToS, ::_ToS ]] enum, ?::encoding? enc) -> ::String
encode_www_form(enum, enc=nil)

Returns a URL-encoded string derived from the given Enumerable enum.

The result is suitable for use as form data for an HTTP request whose Content-Type is 'application/x-www-form-urlencoded'.

The returned string consists of the elements of enum, each converted to one or more URL-encoded strings, and all joined with character '&'.

Simple examples:

Example
URI.encode_www_form([['foo', 0], ['bar', 1], ['baz', 2]])
# => "foo=0&bar=1&baz=2"
URI.encode_www_form({foo: 0, bar: 1, baz: 2})
# => "foo=0&bar=1&baz=2"

The returned string is formed using method URI.encode_www_form_component, which converts certain characters:

Example
URI.encode_www_form('f#o': '/', 'b-r': '$', 'b z': '@')
# => "f%23o=%2F&b-r=%24&b+z=%40"

When enum is Array-like, each element ele is converted to a field:

  • If ele is an array of two or more elements, the field is formed from its first two elements (and any additional elements are ignored):

    Example
    name = URI.encode_www_form_component(ele[0], enc)
    value = URI.encode_www_form_component(ele[1], enc)
    "#{name}=#{value}"
    

    Examples:

    Example
    URI.encode_www_form([%w[foo bar], %w[baz bat bah]])
    # => "foo=bar&baz=bat"
    URI.encode_www_form([['foo', 0], ['bar', :baz, 'bat']])
    # => "foo=0&bar=baz"
    
  • If ele is an array of one element, the field is formed from ele[0]:

    Example
    URI.encode_www_form_component(ele[0])
    

    Example:

    Example
    URI.encode_www_form([['foo'], [:bar], [0]])
    # => "foo&bar&0"
    
  • Otherwise the field is formed from ele:

    Example
    URI.encode_www_form_component(ele)
    

    Example:

    Example
    URI.encode_www_form(['foo', :bar, 0])
    # => "foo&bar&0"
    

The elements of an Array-like enum may be mixture:

Example
URI.encode_www_form([['foo', 0], ['bar', 1, 2], ['baz'], :bat])
# => "foo=0&bar=1&baz&bat"

When enum is Hash-like, each key/value pair is converted to one or more fields:

  • If value is Array-convertible, each element ele in value is paired with key to form a field:

    Example
    name = URI.encode_www_form_component(key, enc)
    value = URI.encode_www_form_component(ele, enc)
    "#{name}=#{value}"
    

    Example:

    Example
    URI.encode_www_form({foo: [:bar, 1], baz: [:bat, :bam, 2]})
    # => "foo=bar&foo=1&baz=bat&baz=bam&baz=2"
    
  • Otherwise, key and value are paired to form a field:

    Example
    name = URI.encode_www_form_component(key, enc)
    value = URI.encode_www_form_component(value, enc)
    "#{name}=#{value}"
    

    Example:

    Example
    URI.encode_www_form({foo: 0, bar: 1, baz: 2})
    # => "foo=0&bar=1&baz=2"
    

The elements of a Hash-like enum may be mixture:

Example
URI.encode_www_form({foo: [0, 1], bar: 2})
# => "foo=0&foo=1&bar=2"