我想通過散列來改變數組的值,例如:如何通過散列更改數組中的值?
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