使用数组值反转哈希

时间:2022-09-27 21:22:10

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 个解决方案

#1


10  

Array#product is pretty badass for this. :)

Array#product非常糟糕。 :)

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}

#2


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


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}

#1


10  

Array#product is pretty badass for this. :)

Array#product非常糟糕。 :)

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}

#2


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


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}