appending to an array inside a loop..

Sergio Ruiz wrote:

for some reason, i am having a hard time with some thing REALLY simple..

i am going through an array of objects, making a one element hash of the
data, and appending that hash to an array..

here's the code...

    @places.each do |p|
      city_string['city_text'] = p.city.titleize + ', ' + p.state.upcase
      @city_list << city_string
    end

after some investigation, what i am finding is that the output of this
is an n element array where n is the size of @places... the bad part is
that each element is a hash with the key-value pair of the last object
in @places..

i did some tracing through the loop, and i found that during each
iteration of the loop, the entire array up to that point takes on
key-value values for the current element..

i am stumped..

anyone have any ideas?

I'm not quite sure what you want to be in @city_list but try this:

@places.each do |p|
   city_string = Hash.new
   city_string['city_text'] = p.city.titleize + ', ' + p.state.upcase
   @city_list << city_string
end

Sergio Ruiz wrote:

I'm not quite sure what you want to be in @city_list but try this:

@places.each do |p|
   city_string = Hash.new
   city_string['city_text'] = p.city.titleize + ', ' + p.state.upcase
   @city_list << city_string
end

perfect!

i was trying to do:

city_string.clear

which i thought was the same thing, but it didn't work....

clear will delete the contents of city_string but it's still the same object (i.e. it keeps the same object id) while city_string = Hash.new creates a new object each time through the loop. That's why @city_list had copies of the last state of city_string. Each element of the array was pointing to the same object_id.