操纵Ruby哈希

时间:2012-10-21 23:47:33

标签: ruby hash key

使用Ruby我需要转换它......

{"30"=>["Morgan", ["lib1", "lib2"]], 
 "31"=>["Morgan", ["lib9", "lib2", "lib3"]], 
 "32"=>["Gary", ["lib1", "lib2"]], 
 "33"=>["Morgan", ["lib1"]], 
 "34"=>["Morgan", []], 
 "35"=>["Morgan", []], 
 "36"=>["Morgan", ["lib3", "lib2"]], 
 "37"=>["jim", ["lib1"]]}

进入这个...

{"Morgan"=>[30,31,33,34,35,36], 
 "Gary"=>[32], []=>[34,35], 
 "jim"=>[37]}

有什么想法吗?

4 个答案:

答案 0 :(得分:2)

input.each_with_object(Hash.new{|h,k|h[k]=[]}) do |(k,v),res|
  (v.last.empty? ? res[[]] : res[v.first]) << k.to_i
end

=> {"Morgan"=>[30, 31, 33, 36], "Gary"=>[32], []=>[34, 35], "jim"=>[37]}

答案 1 :(得分:0)

newhash={}    
hash.inver­t.each {|k,v­| newha­sh[k.first­].concat [v] }

invert方法对您要执行的操作非常有用。但我无法看到值的'lib'部分与转换有何关系。请澄清。

答案 2 :(得分:0)

def convert(input)          
    output = {}                     
    noLibKey = []                   
    input.each do |key, value|      
            number = key.to_i               
            name = value[0]                 
            libs = value[1]                 
            if libs.empty?                  
                    output[noLibKey] ||= []         
                    output[noLibKey] << number      
            end                             
            output[name] ||= []             
            output[name] << number          
    end                             
    return output                   
end

答案 3 :(得分:0)

A = {"30"=>["Morgan", ["lib1", "lib2"]], 
 "31"=>["Morgan", ["lib9", "lib2", "lib3"]], 
 "32"=>["Gary", ["lib1", "lib2"]], 
 "33"=>["Morgan", ["lib1"]], 
 "34"=>["Morgan", []], 
 "35"=>["Morgan", []], 
 "36"=>["Morgan", ["lib3", "lib2"]], 
 "37"=>["jim", ["lib1"]]}

B = Hash.new;
A.each do |k,i|
    if !B[i[0]].kind_of?(Array)
        B[i[0]] = Array.new;
    end
    B[i[0]]<<k
    puts "#{k} #{i[0]}"

end

B.each do |k,i|
    puts "#{k} #{i}"
end

作为示例代码:)