55502f40dc8b7c769880b10874abc9d0

Trying to create the query string on a html link

arr = []
b={:a => "option1", :b => "option2"}
b.each_pair{ |key,value| arr << "#{key}=#{value}" }
arr.join("&")

Refactorings

No refactoring yet !

Ba665f86f90a1982af7b9c857418fcdb

Ryguy

April 29, 2010, April 29, 2010 02:46, permalink

No rating. Login to rate!

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("&")
E8f0d6e9bc8bca695b3c5bdf75cdcc03

Martin Plöger

April 29, 2010, April 29, 2010 04:44, permalink

No rating. Login to rate!

Hash#map or Hash#collect works fine for that.

b = {:a => 'option1', :b => 'option2' }
b.map { |key, value| "#{key}=#{value}" }.join '&'
D41d8cd98f00b204e9800998ecf8427e

Lea

April 29, 2010, April 29, 2010 08:25, permalink

3 ratings. Login to rate!
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"
7855792dbc5f3b4c365344314e2b1ad6

Andrew Vanasse

May 7, 2010, May 07, 2010 12:41, permalink

No rating. Login to rate!

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"
1f393f50dc29119d656c91d6701ddbba

Jeremy Weiskotten

May 8, 2010, May 08, 2010 21:59, permalink

No rating. Login to rate!

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"

Your refactoring





Format Copy from initial code

or Cancel