Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pair elements from two different Arrays into a Hash in Ruby

Tags:

arrays

ruby

hash

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.

like image 663
Genís Avatar asked Mar 18 '26 10:03

Genís


1 Answers

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
like image 53
tokland Avatar answered Mar 20 '26 23:03

tokland