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
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
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
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) }