chaosfirebit chaosfirebit - 1 year ago 55
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
. Is there a way around this?

Answer Source

This is possible to code into your hash using procs.

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

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

# 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({|_,i| -> (val) {arr[i] = val}}).to_h

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

# arr => [1,'hello',3,4,5,6]

# 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.

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