8

For ease of authoring I'm writing my hash like this:

h = {
    :key1: [:val1, :val2, :val3],
    :key2: [:val4, :val5, :val6]
}

But everywhere I use it I need to look up the key associated with a value. Currently I'm doing the following to transform it:

h = Hash[*{
    :key1: [:val1, :val2, :val3],
    :key2: [:val4, :val5, :val6]
}.map {|key, vals| vals.map {|val| [val, key]}}.flatten]

Which gives me what I want:

{ :val1 => :key1, :val2 => key1, :val3 => key1, :val4 => key2, :val5 => :key2, :val6 => :key2 }

But is there a simpler way to achieve the same goal?

3 Answers 3

10

Array#product is pretty badass for this. :)

h = {
    key1: [:val1, :val2, :val3],
    key2: [:val4, :val5, :val6]
}

p Hash[h.flat_map {|k,v| v.product [k]}]
# {:val1=>:key1, :val2=>:key1, :val3=>:key1, :val4=>:key2, :val5=>:key2, :val6=>:key2}
Sign up to request clarification or add additional context in comments.

1 Comment

I think it is a readable and efficient solution compared to other
3
h = {
    :key1 => [:val1, :val2, :val3],
    :key2 => [:val4, :val5, :val6]
}

p Hash[h.flat_map{|k,v| v.zip [k]*v.size }]
# >> {:val1=>:key1, :val2=>:key1, :val3=>:key1, :val4=>:key2, :val5=>:key2, :val6=>:key2}
p Hash[h.flat_map{|k,v| v.zip [k].cycle }]
# >> {:val1=>:key1, :val2=>:key1, :val3=>:key1, :val4=>:key2, :val5=>:key2, :val6=>:key2}

3 Comments

I think the code is hard to read (thus, hard to maintain for production systems). But its cool and short :) (+1)
Very cool. v.zip([k]*v.size) could be simplified to v.zip([k].cycle).
@undur_gongor Nice usecase I have seen today for #cycle. Thank you very much.
2

I was trying to do just this yesterday. This was my solution:

h = {
key1: [:val1, :val2, :val3],    
key2: [:val4, :val5, :val6],    
}  
=> {:key1=>[:val1, :val2, :val3], :key2=>[:val4, :val5, :val6]}

hp = {}
=> {}

h.each { |k, v| v.each{ |e| hp[e] = k } }
=> {:key1=>[:val1, :val2, :val3], :key2=>[:val4, :val5, :val6]}

hp
=> {:val1=>:key1,
:val2=>:key1,
:val3=>:key1,
:val4=>:key2,
:val5=>:key2,
:val6=>:key2}

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.