如何通过哈希更改数组中的值?

时间:2016-11-27 14:42:25

标签: ruby

我想通过哈希更改数组的值,例如:

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

positions[1] = "ee"

问题是改变的是哈希而不是数组。当我p arr时,它仍会输出['g','g','e','z']。有办法解决这个问题吗?

3 个答案:

答案 0 :(得分:2)

您将需要添加另一行代码来执行您想要的操作:

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

positions[1] = "ee"
arr[0] = positions[1]

另一个选择是创建一个为您自动更新数组的方法,如下所示:

def update_hash_and_array(hash, array, val, index)
    # Assume that index is not zero indexed like you have
    hash[index] = val
    array[index - 1] = val
end

update_hash_and_array(positions, arr, "ee", 1) # Does what you want

答案 1 :(得分:2)

可以使用procs将代码编码到哈希中。

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

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


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

如果要生成可以修改任何数组的哈希,可以稍微概括一下。

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']

但是我希望这只是一个思想实验,没有理由改变数组索引行为从1开始而不是0开始的方式。在这种情况下,你通常只想要偏移你拥有的索引匹配正确的数组索引(从零开始)。如果这还不够,则表明您需要不同的数据结构。

答案 2 :(得分:1)

#!/usr/bin/env ruby

a = %w(q w e)

h = {
  1 => a[0]
}

puts a[0].object_id # 70114787518660
puts h[1].object_id # 70114787518660
puts a[0] === h[1]  # true

# It is a NEW object of a string. Look at their object_ids.
# That why you can not change value in an array via a hash.
h[1] = 'Z'

puts a[0].object_id # 70114787518660
puts h[1].object_id # 70114574058580
puts a[0] === h[1]  # false

h[2] = a

puts a.object_id    # 70308472111520
puts h[2].object_id # 70308472111520
puts h[2] === a     # true

puts a[0] === h[2][0] # true
# Here we can change value in the array via the hash.
# Why?
# Because 'h[2]' and 'a' are associated with the same object '%w(q w e)'.
# We will change the VALUE without creating a new object.
h[2][0] = 'X'

puts a[0]             # X
puts h[2][0]          # X
puts a[0] === h[2][0] # true