alexandros84 alexandros84 - 1 year ago 100
Ruby Question

Iterating over a ruby hash

I have a hash whose keys are a range of integers (lets say

) and its corresponding 5 values are all
. I have also an array of integers (lets say
. What I want to do is very specific: I want to take every single key and add it to every single of the array elements, giving me a hash that has the original keys, but has now for values the entire shifted array.

After spending a few hours I have concluded that this is impossible through a really laconic expression, because it is leading to .each shadowing statements.

I think that the only way to go through with this is to create 5 almost identical methods and call them separately.

def a1
array.each do |x|

def a2
array.each do |x|

and so on..

The end product I want to achieve is this:


It feels like there should be a more DRY way to achieve this. Any ideas?

Answer Source

Assuming these initial conditions:

h = {1=>nil, 2=>nil, 3=>nil, 4=>nil, 5=>nil}
arr = [1,2,3,4,5]'s pretty straightforward:

h.keys.each do |key|
  h[key] = {|i| i+key}
# h is now: {1=>[2, 3, 4, 5, 6], 2=>[3, 4, 5, 6, 7], 3=>[4, 5, 6, 7, 8], 4=>[5, 6, 7, 8, 9], 5=>[6, 7, 8, 9, 10]}

(However, it may be that your question is about achieving the initial conditions. If so, I didn't grasp that, and I didn't worry about it; I just started with what I took to be your initial conditions and ended up with your desired result.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download