[Solved] Converting a code from Python to Ruby [closed]


Your Python code outputs:

a=1&b=2&aaa=bbb

In Ruby we might do this as:

require 'cgi'

parameters = {a: 1, b: 2}

encoded = parameters.merge(Hash[*['aaa', 'bbb']])
    .map { |key, value| "#{CGI.escape key.to_s}=#{CGI.escape value.to_s}" }
    .join('&')

p encoded

Which outputs the same:

a=1&b=2&aaa=bbb

It’s longer than the Python code, but IMHO also slightly more readable … You could make it shorter if you wanted to by making a version CGI::escape that accepts a Hash, and not just strings.

solved Converting a code from Python to Ruby [closed]