arr = []
b={:a => "option1", :b => "option2"}
b.each_pair{ |key,value| arr << "#{key}=#{value}" }
arr.join("&")
Refactorings
No refactoring yet !
Ryguy
April 29, 2010, April 29, 2010 02:46, permalink
I'm sure there are better ways, but heres my shot at it
b = {:a => "option1", :b => "option2"}
puts b.keys.collect{ |k| "#{k}=#{b[k]}" }.join("&")
Martin Plöger
April 29, 2010, April 29, 2010 04:44, permalink
Hash#map or Hash#collect works fine for that.
b = {:a => 'option1', :b => 'option2' }
b.map { |key, value| "#{key}=#{value}" }.join '&'
Lea
April 29, 2010, April 29, 2010 08:25, permalink
1 b = {:a => 'option1', :b => 'option2' }
2 b.to_param
#=> "a=option1&b=option2"
# OR
1 b = {:a => 'option1', :b => 'option2' }
2 b.to_query
#=> "a=option1&b=option2"
Andrew Vanasse
May 7, 2010, May 07, 2010 12:41, permalink
No more efficient... I just like inject. :)
b = {:a => 'option1', :b => 'option2' }
b.inject(''){|param_string, (key, val)| param_string << "#{param_string.empty? ? '' : '&'}#{key}=#{val}"}
#=> "a=option1&b=option2"
Jeremy Weiskotten
May 8, 2010, May 08, 2010 21:59, permalink
If this is Rails, you can just call to_query on the Hash.
b = {:a => 'option1', :b => 'option2' }
b.to_query
#=> "a=option1&b=option2"
Trying to create the query string on a html link