A better way to Convert a URL Query String to a Hash ✨

In Ruby on Rails, you might need to work with URL query strings when building web applications that interact with external APIs or handle user input. When working with a URL that contains a query string, you can use Ruby's URI and Rack::Utils modules to extract parameters and store them in a hash.

Here's an example of how to extract parameters from a URL query string and store them in a hash and doing opposite:

Code snippet 📌

# Extract params from URL
 url = "https://rishi.tips/search?q=rails&page=2"
 uri = URI.parse(url)
 => {"q"=>"ruby on rails", "page"=>"2"}

# Add query string to URL from params
 query = {"q"=>"rails", "page"=>"2"}.to_query
 => "https://rishi.tips/search?q=rails&page=2"