简体   繁体   English

Ruby-将哈希推送到数组

[英]Ruby - Pushing Hash to Array

While iterating, I am saving some data to a hash each time. 在迭代时,我每次都将一些数据保存到哈希中。 Within the same loop, I push the hash to an array. 在同一循环中,我将哈希推入数组。

The below code does not work, the last hash object overwrites all the other ones in the array. 下面的代码不起作用,最后一个哈希对象将覆盖数组中的所有其他哈希对象。

playlists = []
aPlaylist = {}

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

The code below does work. 下面的代码可以正常工作。 Why, and what is the difference? 为什么,和有什么区别?

playlists = []

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

Here are the correct and wrong outputs (converted to csv): http://imgur.com/a/rjmBA . 以下是正确和错误的输出(转换为csv): http : //imgur.com/a/rjmBA

Because, in the first case, the object is same that is on 0, 1, and 2nd index. 因为在第一种情况下,对象与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

While in second case it changes: 在第二种情况下,它会更改:

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

Which is why from second case when you make changes to hash, it does not get reflected in all places in array. 这就是为什么从第二种情况开始,当您对哈希进行更改时,它不会在数组的所有位置都得到反映。

Read this stackoverflow answer for more detail. 阅读此stackoverflow答案以获取更多详细信息。

aPlaylist = {} creates a hash and aPlaylist variable holds a pointer to the hash object. aPlaylist = {}创建一个哈希,而aPlaylist变量保存一个指向哈希对象的指针。

In your first example you edit only this one hash object. 在第一个示例中,您仅编辑此哈希对象。

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

In your second example you create a new hash object within each iteration. 在第二个示例中,您将在每次迭代中创建一个新的哈希对象。 That's way this code works. 这样,此代码即可工作。

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

Have a look to the printed object-ids. 看一下打印的对象ID。

I think an idiomatic Ruby approach would be something like ... 我认为惯用的Ruby方法就像...

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

... or ... ... 要么 ...

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

Hence: 因此:

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