If I'm turning a ruby hash into a string of name-value pairs (to be used in HTTP params, for example), is this the best way?
# Define the hash
fields = {"a" => "foo", "b" => "bar"}
# Turn it into the name-value string
http_params = fields.map{|k,v| "#{k}=#{v}"}.join('&')
I guess my question is:
Is there an easier way to get to http_params
? Granted, the above way works and is fairly straightforward, but I'm curious if there's a way to get from the hash to the string without first creating an array (the result of the map
method)?
The string created by calling Hash#inspect can be turned back into a hash by calling eval on it. However, this requires the same to be true of all of the objects in the hash.
Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.
A hash table is a type of data structure that stores key-value pairs. The key is sent to a hash function that performs arithmetic operations on it. The result (commonly called the hash value or hash) is the index of the key-value pair in the hash table.
Rails provides to_query
method on Hash
class. Try:
fields.to_query
From the The Pragmatic Programmer's Guide:
Multiple parameters passed to a yield are converted to an array if the block has just one argument.
For example:
> fields = {:a => "foo", :b => "bar"}
> fields.map { |a| a } # => [[:a, "foo"], [:b, "bar"]]
So your code could be simplified like this:
> fields.map{ |a| a.join('=') }.join('&') # => "a=foo&b=bar"
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