Combine two Arrays into Hash

前端 未结 7 1889
执笔经年
执笔经年 2020-12-01 01:44

I\'ve got two Arrays:

members     = [\"Matt Anderson\", \"Justin Biltonen\", \"Jordan Luff\", \"Jeremy London\"]
instruments = [\"guitar, vocals\", \"guitar\         


        
相关标签:
7条回答
  • 2020-12-01 02:17

    Use map and split to convert the instrument strings into arrays:

    instruments.map {|i| i.include?(',') ? (i.split /, /) : i}
    

    Then use Hash[] and zip to combine members with instruments:

    Hash[members.zip(instruments.map {|i| i.include?(',') ? (i.split /, /) : i})]
    

    to get

    {"Jeremy London"=>"drums",
     "Matt Anderson"=>["guitar", "vocals"],
     "Jordan Luff"=>"bass",
     "Justin Biltonen"=>"guitar"}
    

    If you don't care if the single-item lists are also arrays, you can use this simpler solution:

    Hash[members.zip(instruments.map {|i| i.split /, /})]
    

    which gives you this:

    {"Jeremy London"=>["drums"],
     "Matt Anderson"=>["guitar", "vocals"],
     "Jordan Luff"=>["bass"],
     "Justin Biltonen"=>["guitar"]}
    
    0 讨论(0)
  • 2020-12-01 02:18

    Example 01

    k = ['a', 'b', 'c']
    v = ['aa', 'bb']
    h = {}
    
    k.zip(v) { |a,b| h[a.to_sym] = b } 
    # => nil
    
    p h 
    # => {:a=>"aa", :b=>"bb", :c=>nil}
    

    Example 02

    k = ['a', 'b', 'c']
    v = ['aa', 'bb', ['aaa','bbb']]
    h = {}
    
    k.zip(v) { |a,b| h[a.to_sym] = b }
    p h 
    # => {:a=>"aa", :b=>"bb", :c=>["aaa", "bbb"]}
    
    0 讨论(0)
  • 2020-12-01 02:20
    members.inject({}) { |m, e| t = instruments.delete_at(0).split(','); m[e] = t.size > 1 ? t : t[0]; m }
    

    If you don't care about 1-element arrays in the result, you can use:

    members.inject({}) { |m, e| m[e] = instruments.delete_at(0).split(','); m }
    
    0 讨论(0)
  • 2020-12-01 02:34
    h = {}
    
    members.each_with_index {|item, index|
         h.store(item,instruments[index].split)
    }
    
    0 讨论(0)
  • 2020-12-01 02:37
    h = {}
    members.each_with_index do |el,ix|
        h[el] = instruments[ix].include?(",") ? instruments[ix].split(",").to_a : instruments[ix]
    end
    h
    
    0 讨论(0)
  • 2020-12-01 02:38

    This is the best and cleanest way to do what you want.

    Hash[members.zip(instruments.map{|i| i.include?(',') ? i.split(',') : i})]
    

    Enjoy!

    0 讨论(0)
提交回复
热议问题