Stephen Grayson Stephen Grayson - 1 year ago 59
Ruby Question

How to shift the values in a hash to another key

I am having trouble figuring the best approach to shift some values to another key. Every value most go to the next key, and the last key's values need to be completely removed. For example

hash1 = { a: [1, 2, 3], b: [4, 5, 6], c: [7, 8, 9] }

desired_hash = hash1.some_method

desired_hash === { a: [], b: [1, 2, 3], c: [4, 5, 6] }


My thought is to rename the hash keys but was not sure if this was the best approach.

Answer Source
hash1 = { a: [1, 2, 3], b: [4, 5, 6], c: [7, 8, 9] }
keys = hash1.keys
=> [:a, :b, :c]
values = hash1.values
=> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

keys.zip(values.unshift([])).to_h
=> {:a=>[], :b=>[1, 2, 3], :c=>[4, 5, 6]}