我想通过散列来改变数组的值,例如:如何通过散列更改数组中的值?
arr = ['g','g','e','z']
positions = {1 => arr[0], 2 => arr[1]}
positions[1] = "ee"
问题是,改变了一个散列,而不是阵列。当我做p arr
它仍然输出['g','g','e','z']
。有没有解决的办法?
我想通过散列来改变数组的值,例如:如何通过散列更改数组中的值?
arr = ['g','g','e','z']
positions = {1 => arr[0], 2 => arr[1]}
positions[1] = "ee"
问题是,改变了一个散列,而不是阵列。当我做p arr
它仍然输出['g','g','e','z']
。有没有解决的办法?
你将需要添加另一行代码,做你想做什么:
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
这是可能的代码到您的散列使用特效。
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。在这种情况下启动,您通常只是想弥补索引你必须匹配正确的数组索引(从零开始)。如果这还不够,这是一个标志,你需要一个不同的数据结构。
这真的很有趣。我不知道这是否存在。 –
@ gr1zzlybe4r heh,就我所知,它并不是一个真正常见的ruby范例...它更像javascript-y。就像我说的那样,在实践中没有真正的理由去做这种事情,即使这样写一个方法也会更清晰(就像你的答案一样) – Damon
#!/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
你想要达到什么目的? –
@MarkoAvlijaš它的标题。我想通过散列来改变数组。但是当我这样做的时候,改变的就是哈希本身,而不是数组 – chaosfirebit
@chaosfirebit,你为什么要这样做? – Stefan