0

I have an array of numbers where I want the individual numbers to be the key and the array itself to be the value. Doing this poses no problems

keys.each do |i| 
    myHash[i] = keys
end

But now I want the values to be the array minus the first value for every subsequent iteration so I did this

keys = Array.new

numbers.each do |i|
    keys.push(i)
end

keys.each do |i|
    # puts i
    # puts numbers.inspect
    myHash[i] = numbers
    numbers.shift
end

And it gives me empty arrays as the values in my hash for all the keys. Why is that? Ultimately, I want my hash to look like this given an array of [1, 2, 3, 4]

{1=>[1, 2, 3, 4], 2=>[2, 3, 4], 3=>[3, 4], 4=>[4]}

Thank you!

0

1 Answer 1

2

You are not doing a deep copy of the array.

Try :

keys.each do |i|
   # puts i
   # puts numbers.inspect
   myHash[i] = numbers.clone
   numbers.shift
end
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much! I'll check this after the 10 minutes is up!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.