# My hashe is only storing 1 set of values

**URL:** <https://www.ruby-forum.com/t/my-hashe-is-only-storing-1-set-of-values/120152>\
**Category:** Ruby\
**Created:** [November 14, 2007, 6:34am UTC](https://www.ruby-forum.com/t/my-hashe-is-only-storing-1-set-of-values/120152 "2007-11-14T06:34:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pood](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pood](https://www.ruby-forum.com/u/pood)\
**Post date:** [November 14, 2007, 6:34am UTC](https://www.ruby-forum.com/t/my-hashe-is-only-storing-1-set-of-values/120152/1 "2007-11-14T06:34:22Z")

</div>

Dir.foreach(directory) do |f|  
@file\_sizes = {f =\> File.size(directory+"/"+f)}  
end

So I’m storing the file name and size in a hash, with the name of the  
file as the key.

The above piece of code seems to only store the last file in the  
directory, why is that?

I’m building a program that will get all the files in a directory, grab  
their file sizes. Then I’m gonna to output the 10 biggest files.

My design is:  
put each filename and size into a hash, reverse the key and value (I  
know I can get rid of this step), then output the first 10 sorted array  
values. Is this a good way to do this or is there a better way?

---

<div class="post-metadata">

**Author:** ![pood](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pood](https://www.ruby-forum.com/u/pood)\
**Post date:** [November 14, 2007, 6:37am UTC](https://www.ruby-forum.com/t/my-hashe-is-only-storing-1-set-of-values/120152/2 "2007-11-14T06:37:48Z")

</div>

OMG, sorry i just figured out what I did wrong.

delete thread

---

<div class="post-metadata">

**Author:** ![pood](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3bc359/32.png) [@pood](https://www.ruby-forum.com/u/pood)\
**Post date:** [November 14, 2007, 6:46am UTC](https://www.ruby-forum.com/t/my-hashe-is-only-storing-1-set-of-values/120152/3 "2007-11-14T06:46:47Z")

</div>

Quoth Feng T.:

> Dir.foreach(directory) do |f|  
> @file\_sizes = {f =\> File.size(directory+"/"+f)}  
> end

Should be:

@file\_sizes ||= {}  
Dir.foreach(directory) do |f|  
@file\_sizes[f] = File.size(directory + “/” + f)  
end

HTH,
