假设我有一个在 Ruby 中看起来像这样的哈希:
{ :ie0 => "Hi", :ex0 => "Hey", :eg0 => "Howdy",
:ie1 => "Hello", :ex1 => "Greetings", :eg1 => "Good day"}
有什么好的方法可以将它变成如下内容:
{ "0" =>
{
"ie" => "Hi", "ex" => "Hey", "eg" => "Howdy"
},
"1" =>
{
"ie" => "Hello", "ex" => "Greetings", "eg" => "Good day"
}
}
最佳答案
您要求一个好的方法来做到这一点,所以答案是:一种您或同事可以在六个月后理解和维护的方法。
首先,您需要一个 Hash with autovivification因为您正在创建嵌套的哈希结构。这是一个非常有用的编码模式,它将简化您的应用程序代码:
# 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] = { } }
然后,您可以以这种简单的方式遍历现有的键,分解每个键的各个部分,并使用它们将值保存在新的哈希中:
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
我得到这个输出:
{"0"=>{"ie"=>"Hi", "ex"=>"Hey", "eg"=>"Howdy"}, "1"=>{"ie"=>"Hello", "ex"=>"Greetings", "eg"=>"Good day"}}
关于ruby - 在 Ruby 中创建按公共(public)键值分组的新哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19193353/