Reputation: 35
Want to make such a conversion, but do not get right result
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
}
Implementing my conversion with nested loop. I thought that while inside loop is looping the outer loop will not increment. Here is my code:
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
Upvotes: 1
Views: 61
Reputation: 110675
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}
Upvotes: 2
Reputation: 369064
You don't need to use index, just use v
:
def self.transform(old)
result = {}
old.each do |key, value|
value.each do |v|
result[v.downcase] = key
end
end
result
end
NOTE: used String#downcase
to match the expected hash's key case.
Alternative using 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
Upvotes: 5