How to decode URL-encoded and URL query strings in Ruby

2 Answers

0 votes
require 'uri'

# Function to decode a URL-encoded string or form component
def decode_url_string(encoded_str)
  # URI.decode_www_form_component handles both %xx escapes and '+' to space conversion
  URI.decode_www_form_component(encoded_str)
rescue ArgumentError => e
  # Handle malformed percent-encoding gracefully
  puts "Decoding error: #{e.message}"
  encoded_str
end

# --- Program Execution ---
if __FILE__ == $0
  # Example 1: Standard URL encoding with special characters
  sample1 = "Hello%20World%21%20Ruby%20%26%20Web"
  puts "--- Example 1: Standard URL Encoding ---"
  puts "Encoded: #{sample1}"
  puts "Decoded: #{decode_url_string(sample1)}"

  # Example 2: Form query string fragment encoding (spaces represented as '+')
  sample2 = "Jane+Doe+from+New+York"
  puts "\n--- Example 2: Form Fragment Encoding ---"
  puts "Encoded: #{sample2}"
  puts "Decoded: #{decode_url_string(sample2)}"
end


# run:
#
# --- Example 1: Standard URL Encoding ---
# Encoded: Hello%20World%21%20Ruby%20%26%20Web
# Decoded: Hello World! Ruby & Web
# 
# --- Example 2: Form Fragment Encoding ---
# Encoded: Jane+Doe+from+New+York
# Decoded: Jane Doe from New York
# 

 



answered 6 hours ago by avibootz
0 votes
require 'uri'

# Function to parse and decode a complete URL query string into a Hash
def parse_and_decode_query(query_string)
  # Remove leading '?' if present
  query_string = query_string.sub(/^\?/, '')
  
  # URI.decode_www_form returns an array of [key, value] pairs, 
  # which can be converted directly into a Ruby Hash.
  # Note: to_h uses the last value if duplicate keys exist.
  URI.decode_www_form(query_string).to_h
rescue ArgumentError => e
  puts "Parsing error: #{e.message}"
  {}
end

# --- Runnable Program Execution ---
if __FILE__ == $0
  full_query = "search=ruby+tutorial&category=programming&tag=beginner"
  
  puts "--- Full Query String Parsing ---"
  puts "Original Query: #{full_query}"
  
  result_hash = parse_and_decode_query(full_query)
  
  puts "Decoded Hash Result:"
  result_hash.each do |key, value|
    puts "  #{key} => #{value}"
  end
end


# run:
#
# --- Full Query String Parsing ---
# Original Query: search=ruby+tutorial&category=programming&tag=beginner
# Decoded Hash Result:
#   search => ruby tutorial
#   category => programming
#   tag => beginner
# 

 



answered 6 hours ago by avibootz
...