alexandros84 alexandros84 - 12 days ago 5
Ruby Question

Iterating over a ruby hash

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

[1..5]
) and its corresponding 5 values are all
nil
. I have also an array of integers (lets say
[1,2,3,4,5]
. 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|
x+1
end
end

def a2
array.each do |x|
x+2
end
end


and so on..

The end product I want to achieve is this:

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


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

Answer

Assuming these initial conditions:

h = {1=>nil, 2=>nil, 3=>nil, 4=>nil, 5=>nil}
arr = [1,2,3,4,5]

...it's pretty straightforward:

h.keys.each do |key|
  h[key] = arr.map {|i| i+key}
end
# 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.)

Comments