簡體   English   中英

Ruby-將哈希推送到數組

[英]Ruby - Pushing Hash to Array

在迭代時,我每次都將一些數據保存到哈希中。 在同一循環中,我將哈希推入數組。

下面的代碼不起作用,最后一個哈希對象將覆蓋數組中的所有其他哈希對象。

playlists = []
aPlaylist = {}

while (count < 3)
    #some code... produces the hash "aPlaylist"
    playlist << aPlaylist
end

下面的代碼可以正常工作。 為什么,和有什么區別?

playlists = []

while (count < 3)
    aPlaylist = {}
    #some code... produces the hash "aPlaylist"
    playlist << aPlaylist
end

以下是正確和錯誤的輸出(轉換為csv): http : //imgur.com/a/rjmBA

因為在第一種情況下,對象與0、1、2nd索引相同。

playlist = []
aPlaylist = {}
count = 0

while (count < 3)
    #some code... produces the hash "aPlaylist"
    playlist << aPlaylist
    puts aPlaylist.object_id
    count += 1
end
#=> 2048
#=> 2048
#=> 2048

在第二種情況下,它會更改:

playlist = []

count = 0

while (count < 3)
    aPlaylist = {}
    #some code... produces the hash "aPlaylist"
    playlist << aPlaylist
    puts aPlaylist.object_id
    count += 1
end
#=> 2048
#=> 2038
#=> 2028

這就是為什么從第二種情況開始,當您對哈希進行更改時,它不會在數組的所有位置都得到反映。

閱讀此stackoverflow答案以獲取更多詳細信息。

aPlaylist = {}創建一個哈希,而aPlaylist變量保存一個指向哈希對象的指針。

在第一個示例中,您僅編輯此哈希對象。

aPlaylist = {}
count = 0
while (count < 3)
  puts aPlaylist.object_id
  count += 1
end
#=> 70179174789100
#=> 70179174789100
#=> 70179174789100

在第二個示例中,您將在每次迭代中創建一個新的哈希對象。 這樣,此代碼即可工作。

count = 0
while (count < 3)
  aPlaylist = {}
  puts aPlaylist.object_id
  count += 1
end
#=> 70179182889040
#=> 70179182888980
#=> 70179182888920

看一下打印的對象ID。

我認為慣用的Ruby方法就像...

playlist = 0.upto(2).map{|count| something_that_returns_a_hash }

... 要么 ...

playlist = (0..2).map{|count| something_that_returns_a_hash }

因此:

0.upto(2).map{|count| {count => count} }

[{0=>0}, {1=>1}, {2=>2}] 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM