# Creating static variables

**URL:** <https://www.ruby-forum.com/t/creating-static-variables/188345>\
**Category:** Ruby\
**Created:** [May 10, 2010, 4:02pm UTC](https://www.ruby-forum.com/t/creating-static-variables/188345 "2010-05-10T16:02:36Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![deviated](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c89c15/32.png) [@deviated](https://www.ruby-forum.com/u/deviated)\
**Post date:** [May 10, 2010, 4:02pm UTC](https://www.ruby-forum.com/t/creating-static-variables/188345/1 "2010-05-10T16:02:36Z")

</div>

Hi,

Trying to make a program where a user can input hours done (counter),  
and then show the number of hours done. The only problem is saving the  
new value, how do I do it?  
For example.  
-First time program starts, counter is at zero.  
-user adds 5 hours to counter  
-program is closed  
-program started again  
-user adds two hours to counter  
-value in counter, 7 hours (what I want it to do)  
Thanks

---

<div class="post-metadata">

**Author:** ![deviated](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c89c15/32.png) [@deviated](https://www.ruby-forum.com/u/deviated)\
**Post date:** [May 10, 2010, 5:27pm UTC](https://www.ruby-forum.com/t/creating-static-variables/188345/2 "2010-05-10T17:27:27Z")

</div>

Last time I had this sort of problem I create a @@var in the class that  
contains the method used.

So you could do something like

@@counter = 0  
def update\_counter value  
@@counter += value  
end

p @@counter #=\> 0  
update\_counter 12  
p @@counter #=\> 12  
update\_counter 5  
p @@counter #=\> 17

---

<div class="post-metadata">

**Author:** ![deviated](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c89c15/32.png) [@deviated](https://www.ruby-forum.com/u/deviated)\
**Post date:** [May 11, 2010, 3:29am UTC](https://www.ruby-forum.com/t/creating-static-variables/188345/3 "2010-05-11T03:29:34Z")

</div>

As for the static variables, thanks for the advice.

For in the case of my small program, instead of using a static variable,  
it’s just better to store the info on a file.

Thanks again dude

---

<div class="post-metadata">

**Author:** ![deviated](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/c89c15/32.png) [@deviated](https://www.ruby-forum.com/u/deviated)\
**Post date:** [May 11, 2010, 11:00am UTC](https://www.ruby-forum.com/t/creating-static-variables/188345/4 "2010-05-11T11:00:07Z")

</div>

Omar M. wrote:

> For in the case of my small program, instead of using a static variable,  
> it’s just better to store the info on a file.

You can use this pattern to save and load a Ruby object: it has the  
advantage of saving a complete object graph if this object contains  
objects which in turn contain other objects etc.

File.open(“myobj.rbm”,“wb”) { |f| Marshal.dump(myobj, f) }

…

myobj = File.open(“myobj.rbm”,“rb”) { |f| Marshal.load(f) }
