3

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

4 に答える 4

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]}
于 2012-10-22T00:19:40.410 に答える
0
newhash={}    
hash.inver­t.each {|k,v­| newha­sh[k.first­].concat [v] }

メソッドは、invertあなたがやりたいことに役立ちます。しかし、値の「lib」部分が変換とどのように関係しているのかわかりません。どうか明らかにしてください。

于 2012-10-22T00:08:41.473 に答える
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
于 2012-10-22T00:08:45.520 に答える
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

コード例として:)

于 2012-10-22T00:14:43.563 に答える