chaosfirebit chaosfirebit - 5 days ago 5
Ruby Question

How to change a value in an array via a hash?

I want to change the value of an array via a hash, for example:

arr = ['g','g','e','z']
positions = {1 => arr[0], 2 => arr[1]}

positions[1] = "ee"


Problem is that the one that changed is hash and not array. When I do
p arr
It still outputs
['g','g','e','z']
. Is there a way around this?

Answer

This is possible to code into your hash using procs.

arr = ['g','g','e','z']

positions = {1 => -> (val) { arr[0] = val } }


positions[1].('hello')
# arr => ['hello', 'g', 'e', 'z']

You can generalize this a bit if you want to generate a hash that can modify any array.

def remap_arr(arr, idx)
  (idx...arr.length+idx).zip(arr.map.with_index{|_,i| -> (val) {arr[i] = val}}).to_h
end

arr = [1,2,3,4,5,6]
positions = remap_arr(arr, 1)

positions[2].('hello')
# arr => [1,'hello',3,4,5,6]

positions[6].('goodbye')
# arr => [1,'hello',3,4,5,'goodbye']

But I'm hoping this is just a thought experiment, there is no reason to change the way array indexing behavior works to start from 1 rather than 0. In such cases, you would normally just want to offset the index you have to match the proper array indexing (starting at zero). If that is not sufficient, it's a sign you need a different data structure.

Comments