Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a hash into a string of name-value pairs

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)?

like image 799
jerhinesmith Avatar asked Dec 01 '09 03:12

jerhinesmith


People also ask

How do you turn a string into a hash in Ruby?

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.

How do you create a key value pair in ruby?

Using {} braces: In this hash variable is followed by = and curly braces {}. Between curly braces {}, the key/value pairs are created.

What is key and value in hash?

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.


2 Answers

Rails provides to_query method on Hash class. Try:

fields.to_query

like image 89
Anuj Jamwal Avatar answered Oct 15 '22 00:10

Anuj Jamwal


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"
like image 45
Christian Avatar answered Oct 15 '22 00:10

Christian