ruby 1.8.7 replace params hash

131 views Asked by At

I use ruby 1.8.7 and get the params from my form like this:

 "cart"=>{"1140229"=>["5"], "1140228"=>["4"], "1140222"=>["7"]}

And, I use rails 2.3 (it's too old, I know it!) which requires this syntax:

1140229 => { :quantity => 5 }, 1140228 => { :quantity => 4 }, 1140222 => { :quantity => 7 }

I use this code to replace params hash:

params[:cart].each{ |k,v| params[:cart][k] = { :quantity => v[0] } }
Cart.update(params[:cart].keys, params[:cart].values)

How can I replace this code in 1.8.7 & 1.9.3 (I'll move my rails app to the new version soon)?

4

There are 4 answers

2
techvineet On

You can use this even with old ruby version.

x = {"cart"=>{"1140229"=>["5"], "1140228"=>["4"], "1140222"=>["7"]}}

update_params = x["cart"].collect do |k, v|
 {k => {:quantity => v}}
end

in fact your question has nothing to do with newer Rails version. This can be achieved with core Ruby.

0
BroiSatse On

This should work:

x = {"cart"=>{"1140229"=>["5"], "1140228"=>["4"], "1140222"=>["7"]}}

result = Hash[x['cart'].map {|key, value| [key.to_i, {:quantity => value.first.to_i}]}]
0
Mark Reed On
cart = params['cart'].inject({}) do |c, kv| k,v=kv; c.merge({ k => { :quantity => v }}) end
0
Alex Antonov On

The whole problem solved by me. Thanks, guys!

Cart.update(params[:cart].keys, params[:cart].values.map{ |value| { :quantity => value[0] } })