假设我在Ruby中有一个看起来像这样的哈希:
{ :ie0 => "Hi", :ex0 => "Hey", :eg0 => "Howdy",
:ie1 => "Hello", :ex1 => "Greetings", :eg1 => "Good day"}
Run Code Online (Sandbox Code Playgroud)
有什么好办法把它变成这样的东西:
{ "0" =>
{
"ie" => "Hi", "ex" => "Hey", "eg" => "Howdy"
},
"1" =>
{
"ie" => "Hello", "ex" => "Greetings", "eg" => "Good day"
}
}
Run Code Online (Sandbox Code Playgroud)
您要求一种好的方法来做到这一点,所以答案是:一种您或同事从现在起六个月后可以理解和维护的方法。
首先,您需要一个具有自动生存功能的哈希,因为您正在创建一个嵌套哈希结构。这是一种非常有用的编码模式,可以简化您的应用程序代码:
# Copied & pasted from the question
old_hash = { :ie0 => "Hi", :ex0 => "Hey", :eg0 => "Howdy", :ie1 => "Hello", :ex1 => "Greetings", :eg1 => "Good day"}
# Auto-vivify
new_hash = Hash.new { |h, k| h[k] = { } }
Run Code Online (Sandbox Code Playgroud)
然后,您可以以这种简单的方式循环遍历现有的键,分解每个键的各个部分,并使用它们将值保存在新的哈希中:
old_hash.each_pair do |key, value|
key =~ /^(..)(.)$/ # Make a regex group for each string to parse
new_hash[$2][$1] = value # The regex groups become the new hash keys
end
puts new_hash
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
{"0"=>{"ie"=>"Hi", "ex"=>"Hey", "eg"=>"Howdy"}, "1"=>{"ie"=>"Hello", "ex"=>"Greetings", "eg"=>"Good day"}}
Run Code Online (Sandbox Code Playgroud)