views:

35

answers:

2

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!

+6  A: 

There's only one hash tweet ever created, and its values are just overwritten. You should assign tweet = {} inside the loop.

Yuliy
That's IT! thanks a lot, I really struggled to understand this.
SimonMD
+2  A: 

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.

Justin Blake
Thank you very much for your explanation! so that means that whatever I think I'm assigning to the hash, It gets overwritten BUT still added as an object to the array? So that's why I get a bunch of the same hash...interesting.
SimonMD
I'm afraid my neurons don't seem to be wired as a programmer yet. I appreciate your explanation, I wish I could vote you up (not enough ..reputation?)
SimonMD