Combine Two Arrays into Hash

Combine two Arrays into Hash

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"]}

Combining two arrays into a hash

@hash_array = {}
@sample_array.each_with_index do |value, index|
@hash_array[value] = @timesheet_id_array[index]
end

How to merge two arrays of hashes

uniq would work if you concatenate the arrays in reverse order:

(b + a).uniq { |h| h[:key] }
#=> [
# {:key=>1, :value=>"bar"},
# {:key=>1000, :value=>"something"},
# {:key=>2, :value=>"baz"}
# ]

It doesn't however preserve the order.

Convert two arrays into an array of Hash pairs

dates.zip(values).map{|k, v| {date: k, value: v}}

Merge two arrays into a Hash

assuming you have 2 equal length arrays x and y

x = [:key1, :key2, :key3]
y = [:value1, :value2, :value3]
z = {}
x.each_with_index { |key,index| z[key] = y[index] }

puts z

=> {:key1=>:value1, :key2=>:value2, :key3=>:value3}

is that what you are looking for?

then maybe this:

x = [:key1, :key2, :key3]
y = [:value1, :value2, :value3]
z = []
x.each_with_index { |key,index| z << { date: key, minutes: y[index]} }



puts z

{:date=>:key1, :minutes=>:value1}
{:date=>:key2, :minutes=>:value2}
{:date=>:key3, :minutes=>:value3}

Combine values of two arrays to form key and values to hash in ruby

Sure, very simple

Hash[[1,2,3,4].zip([5,6,7,8])]
=> {1=>5, 2=>6, 3=>7, 4=>8}

But it might be a problem if the arrays have not the same size.



Related Topics



Leave a reply



Submit