["param_1","param_2"], "key2" => -6ren">
gpt4 book ai didi

ruby-on-rails - Ruby 哈希创建

转载 作者:数据小太阳 更新时间:2023-10-29 08:49:01 26 4
gpt4 key购买 nike

我是 Ruby 的新手,最近正在努力学习 Ruby。今天在刷Hash,卡在了Hash相关的问题上

我有以下哈希

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

我想将上面的 Hash 转换成下面的。

{"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"]}
]
}

谁能告诉我如何用 Ruby 高效地做到这一点。

最佳答案

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: Array(v) }}
# => [{: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"]}]

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" => Array(v) }}
# => [{"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"]}]

关于ruby-on-rails - Ruby 哈希创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18472385/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com