Skip to content

Instantly share code, notes, and snippets.

@macabreb0b
Last active August 29, 2015 14:08
Show Gist options
  • Save macabreb0b/640f4f96e819b065bd98 to your computer and use it in GitHub Desktop.
Save macabreb0b/640f4f96e819b065bd98 to your computer and use it in GitHub Desktop.
Rails-style Ruby method for turning a URL query string into a deeply-nested hash
require 'uri'
q1 = 'username=charlie&email=charlie@gmail'
q2 = 'user[username]=charlie&user[email]=charlie@gmail.com&user[password]=password'
q3 = 'user[address][street]=market&user[address][zipcode]=94103&user[email]=charlie@gmail.com'
puts URI.decode_www_form(q1).to_s
puts URI.decode_www_form(q2).to_s
puts URI.decode_www_form(q3).to_s
# goal is deeply-nested hash, like so: { 'user' => { 'username'=> 'charlie', 'email' => 'charlie@gmail.com', 'address' => { 'zipcode' => 94103 } }
def encode_www_params(query_string)
array_of_pairs = URI.decode_www_form(query_string)
result = {}
array_of_pairs.each do |pair|
keys = parse_key(pair[0])
value = pair[1]
puts [keys, value].to_s
current_hash = result
keys.each_with_index do |key, idx|
if idx == keys.length - 1
current_hash[key] = value
else
current_hash[key] ||= {}
current_hash = current_hash[key]
end
puts result.to_s
end
end
result
end
def parse_key(key)
key.split(/\[|\]\[|\]/)
end
puts encode_www_params(q1)
puts encode_www_params(q2)
puts encode_www_params(q3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment