Need help in Hash

Hello Everyone,

I am a newbie in Ruby and I am trying to learn Ruby these day. I was
going through Hash today and I got stuck in problem related to Hash

I have the following Hash

{"key1" => ["param_1","param_2"], "key2" => ["param_3","param_4"],
"key3" => "param_5", "key4" => "param_6","key5" =>
["param_7","param_8"]}

and I want to convert the above Hash into the following.

{"my_hash" => [ {"name" => "key1","value" => ["param_1","param_2"]},
                {"name" => "key2","value" => ["param_3","param_4"]},
                {"name" => "key3","value" => ["param_5"]},
                {"name" => "key4","value" => ["param_6"]},
                {"name" => "key5","value" => ["param_7","param_8"]}
              ]
}

Can someone show me how can i do it in Ruby in a efficient way.

Thanks
Alex

···

--
Posted via http://www.ruby-forum.com/.

data.each_with_object({"my_hash" => []}) {|(k,v),o| o["my_hash"] << {
"name" => k, "value" => v}}

···

--
Posted via http://www.ruby-forum.com/.

Do as below as I answered you here -


:

hsh = {"key1" => ["param_1","param_2"],
       "key2" => ["param_3","param_4"], "key3" => "param_5",
      "key4" => "param_6","key5" => ["param_7","param_8"]}
hsh.map{|k,v| {"name" => k,"value" => [v].flatten }}
# => [{"name"=>"key1", "value"=>["param_1", "param_2"]},
# {"name"=>"key2", "value"=>["param_3", "param_4"]},
# {"name"=>"key3", "value"=>["param_5"]},
# {"name"=>"key4", "value"=>["param_6"]},
# {"name"=>"key5", "value"=>["param_7", "param_8"]}]

···

--
Posted via http://www.ruby-forum.com/.