If I convert a hash to a query string, how can I convert it back again?
{:filters => {:colour => ['Red', 'Blue'], :size => 'Medium'}}.to_param
=> "filters[colour][]=Red&filters[colour][]=Blue&filters[size]=Medium"
Rails appears to do this automatically when it populates the params
hash, but is it possible to call this method directly?
Thanks.
A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type. Hashes enumerate their values in the order that the corresponding keys were inserted.
Hashes are inherently unordered. Hashes provide amortized O(1) insertion and retrieval of elements by key, and that's it. If you need an ordered set of pairs, use an array of arrays.
We can check if a particular hash contains a particular key by using the method has_key?(key) . It returns true or false depending on whether the key exists in the hash or not.
You're looking for Rack::Utils.parse_nested_query(query)
, which will convert it back into a Hash
. You can get it by using this line:
require 'rack/utils'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With