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
How to Install Therubyracer Gem on 10.10 Yosemite
Difference Between $Stdout and Stdout in Ruby
Convert Array of 2-Element Arrays into a Hash, Where Duplicate Keys Append Additional Values
Rails: Skinny Controller Vs. Fat Model, or Should I Make My Controller Anorexic
Gem Eventmachine Fatal Error: 'Openssl/Ssl.H' File Not Found
How to Compile and Statically Link Ruby Libs for Docker
Is There a "Phpmyadmin" for Ruby on Rails
Turning Long Fixed Number to Array Ruby
Gem Install Fails with Openssl Failure
How to Swap Keys and Values in a Hash
How to Stub Things in Minitest
Ruby Gem For Finding Timezone of Location
Stop Devise from Clearing Session
How to Do Relative Time in Rails
Can't Install Rails on MAC Os Catalina
Error: Error Installing Ffi: Error: Failed to Build Gem Native Extension