1

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 
1
  • The inverse hash part is interesting, but as a whole this is a bad question because downcasing has nothing to do with it. You should separate them into individual questions. Commented Feb 28, 2017 at 14:01

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

You can incorporate sort before to_h.
@Stefan, Thank you for the comment. I added .sort before .to_h accordingly.
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} 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.