Let's say I have this two Arrays:
a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 10]
What I want to get is a Hash as follows:
c = { 1 => [1, 6], 2 => [2, 7], 3 => [3, 8], 4 => [4, 9], 5 => [5, 10] }
The only way I've come across so far is as follows:
# Initialize the resulting Hash and fill in the keys.
c = {}
(a.length).times { |i| c[i + 1] = [] }
# Fill values
c.each_with_index do |(key), idx|
c[key] = [a[idx], b[idx]]
end
Does Ruby have a better or pretty way to do this?
Thanks in advance.
Functional approach:
Hash[a.zip(b).map.with_index(1) { |pair, idx| [idx, pair] }]
#=> {1=>[1, 6], 2=>[2, 7], 3=>[3, 8], 4=>[4, 9], 5=>[5, 10]}
Just for fun, and if you like to build your own abstractions: the previous snippet is more verbose than it should because of with_index, firstly it works only on enumerators (not enumerables), secondly it puts the value as the second element (it would be more useful as the first, that's what most of other languages do). What could we do? add our own Enumerable#indexed method that worked the other way around. At this point we'd be compelled to also add Enumerable#to_h, so finally we'd be able to write this pure OOP, left-to-right, declarative code:
a.zip(b).indexed(1).to_h
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With