Forum: Ruby on Rails local variables with hashes

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6e9f4e0de736402938ded7b32aa9a33d?d=identicon&s=25 Pentti Laitinen (lazah)
on 2008-11-26 10:14
I have a question about using local variables as values for ruby hashes.
I have to do a script that will gather meta data of video files in a
fixed directory and store them in an array of hashes. The problem is
that when I have collected the meta data to a hash called video and
append this to the end of videos array all the hash entries are the same
in the array. I assign the values to the hash and append to the videos
array with this script block:

video["res_w"] = res_w
video["res_h"] = res_h
video["dur_h"] = dur_h
video["dur_m"] = dur_m
video["dur_s"] = dur_s
video["dur_ms"] = dur_ms
videos << video

All the local variables have been initialized as zeroes and when my loop
retrieves another file for processing it reuses the local variables. The
actual question is does the hash store a pointer to the local variable
as its value? If it does is there a way to overwrite this behaviour or
some way around it?
C64e63b70be7dfed8b0742540b8b27e5?d=identicon&s=25 Mark Reginald James (Guest)
on 2008-11-29 10:52
(Received via mailing list)
Pentti Laitinen wrote:
> video["dur_h"] = dur_h
> video["dur_m"] = dur_m
> video["dur_s"] = dur_s
> video["dur_ms"] = dur_ms
> videos << video
>
> All the local variables have been initialized as zeroes and when my loop
> retrieves another file for processing it reuses the local variables. The
> actual question is does the hash store a pointer to the local variable
> as its value? If it does is there a way to overwrite this behaviour or
> some way around it?

Integer hash values aren't stored as object references.

Perhaps your problem is that you're not re-initializing
video to {} each time around the loop, so you're always
updating a common video object.

--
Rails Wheels - Find Plugins, List & Sell Plugins -
http://railswheels.com
This topic is locked and can not be replied to.