想要进行此类转换,但结果不正确
old = {
1 => %w(A E I O U L N R S T),
2 => %w(D G),
3 => %w(B C M P),
4 => %w(F H V W Y),
5 => %w(K),
8 => %w(J X),
10 => %w(Q Z)
}
expected = {
'a' => 1, 'b' => 3, 'c' => 3, 'd' => 2, 'e' => 1,
'f' => 4, 'g' => 2, 'h' => 4, 'i' => 1, 'j' => 8,
'k' => 5, 'l' => 1, 'm' => 3, 'n' => 1, 'o' => 1,
'p' => 3, 'q' => 10, 'r' => 1, 's' => 1, 't' => 1,
'u' => 1, 'v' => 4, 'w' => 4, 'x' => 8, 'y' => 4,
'z' => 10
}
使用嵌套循环实现我的转换。我认为当内循环循环时,外循环不会增加。这是我的代码:
class Etl
def self.transform(old)
result = {}
old.each do |key, value|
value.each_with_index do |v, i|
result[v[i]] = key
end
end
result
end
end
答案 0 :(得分:5)
您不需要使用索引,只需使用v
:
def self.transform(old)
result = {}
old.each do |key, value|
value.each do |v|
result[v.downcase] = key
end
end
result
end
注意:使用String#downcase
来匹配预期的哈希密钥案例。
使用Array#map
,Enumerable#flat_map
,Enumerable#to_h
的替代方案:
def self.transform(old)
old.flat_map { |key, value|
value.map { |v|
[v.downcase, key]
}
}.sort.to_h
end
答案 1 :(得分:2)
old.flat_map { |k, v| v.map(&:downcase).product([k]) }.sort.to_h
#=> {"a"=>1, "b"=>3, "c"=>3, "d"=>2, "e"=>1, "f"=>4, "g"=>2, "h"=>4, "i"=>1,
# "j"=>8, "k"=>5, "l"=>1, "m"=>3, "n"=>1, "o"=>1, "p"=>3, "q"=>10, "r"=>1,
# "s"=>1, "t"=>1, "u"=>1, "v"=>4, "w"=>4, "x"=>8, "y"=>4, "z"=>10}