用来自each/do块的散列迭代地填充数组给我所有重复值..帮助!
我试图用通过每个循环创建的哈希值填充哈希值数组,如果我在迭代中打印每个单独的哈希值,它们是不同的,但是当我尝试将它们推送到数组时,生成的数组会重复最后一个哈希值次数。这是代码:
def get_tweets
tweet_array = Array.new
tweet = {}
Twitter::Search.new('Accidente' || 'accidente').from('sttmed').each do |r|
tweet["texto"] = r.text
tweet["reportado"] = (Time.parse(r.created_at)).localtime.strftime("%B %d, %H:%M %p %Z")
tweet["direccion"] = r.text.scan(/\w*_\w*/).join
tweet_array << tweet
end
return tweet_array # RETURNS ALL REPEAT VALUES!!
end
我到处都看了,但我似乎找不到我做错了什么(这可能是一个愚蠢的问题,但它困扰着这个初学者..)我将不胜感激任何帮助!
I am trying to fill an array of hashes with hashes created through an each loop, If I print each individual hash within the iteration they are distinct, but when I try to push them to an array, the resulting array has the last hash repeated whatever number of times. Here's the code:
def get_tweets
tweet_array = Array.new
tweet = {}
Twitter::Search.new('Accidente' || 'accidente').from('sttmed').each do |r|
tweet["texto"] = r.text
tweet["reportado"] = (Time.parse(r.created_at)).localtime.strftime("%B %d, %H:%M %p %Z")
tweet["direccion"] = r.text.scan(/\w*_\w*/).join
tweet_array << tweet
end
return tweet_array # RETURNS ALL REPEAT VALUES!!
end
I have looked everywhere but I can't seem to find what I'm doing wrong (It's probably a dumb problem but it's stumping this beginner..) I'll appreciate any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只创建了一条哈希
tweet
,并且它的值刚刚被覆盖。您应该在循环内分配tweet = {}
。There's only one hash
tweet
ever created, and its values are just overwritten. You should assigntweet = {}
inside the loop.尤莉是对的。更多解释:
变量是 ruby 中对象的引用。您的代码正在创建一个哈希对象并使用
tweet
变量引用它,然后在循环内为其提供一些值并将其附加到数组中。下次循环时,您将在同一推文对象上设置新值,并再次附加它。现在,数组中的两个项目都使用这组新值引用同一对象。每次都如此等等。最终得到一个充满对同一对象的引用的数组,其中包含您在循环的最后一次迭代中分配的值。正如 Yuliy 所说,在循环内分配
tweet = {}
将每次创建一个新的哈希对象,这正是您所期望的。Yuliy is right. A bit more explanation:
A variable is a reference to an object in ruby. You're code is creating a single hash object and referencing it with the
tweet
variable, then inside the loop you're giving it some values and appending it to the array. The next time the through the loop you're setting new values on that same tweet object, and appending it again. Now both items in your array are referencing the same object with that new set of values. And so on and so on each time. Ending up with an array full of references to the same object, which has the values you assigned on the last iteration through the loop.As Yuliy said, assigning
tweet = {}
inside the loop will create a new hash object each time, which is what you're expecting.