Turning a hash into a string of name-value pairs
This is probably the best you can do. You could iterate through the pairs in the hash, building the string as you go. But in this case the intermediate string would need to be created and deleted at each step.
Do you have a use-case where this is a performance bottleneck? In general Ruby is doing so much work behind the scenes that worrying about a temporary array like this is probably not worth it. If you are concerned that it may be a problem, consider profiling your code for speed and memory usage, often the results are not what you expect.
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"
Rails provides to_query
method on Hash
class. Try:
fields.to_query