while loop end action

J

John Crichton

I am trying to write a script that when certain circumstances arise it
creates an object instance that adds some info to a temporary array for
a given time. When the given time is up I would like to perform a couple
actions and print the array. After that the array and object instance
will no longer be needed, so I would like to ensure the obj is freed
from memory. I am pretty new to coding and to Ruby, what is the best
way to accomplish this. I thought it would be a while loop but I am
confused as to how to perform an action once my counter or time has
reached it's end. For example, where can I put the ending action?

class Blah
def initialize
@myarray = Array.new
@init_time = Time.now.to_f
@twomin = @init_time + 120
end

def add_to_array(x)
while Time.now.to_f < @twomin
@myarray << x
end
#pp @myarray.inspect
end

end

Since the while loop has a definite end. Does this end the object's
instance, I suspect no and I need to put some die statement in there or
delete the object from outside the object?

If I do an if/else loop than it will continue to run I suspect too.
if Time.now.to_f < @twomin
@myarray << x
else
pp @myarray.inspect
end

How can I properly run some actions or a method after my counter/time
has reached it's end and then delete the obj instance?

Thanks
 
R

R.. Kumar 1.9.1 OSX

John said:
How can I properly run some actions or a method after my counter/time
has reached it's end and then delete the obj instance?

Thanks

since no one has responded I'll make a quick try...

1. you can always do:

myarray = nil

2. Your variables and the print can be local variables inside the
method. Use @var only for instance level data. in your case, you do not
need the data outside of the method.

def method
array = []
# or array = Array.new
while ....
array << "str"
end
puts array.join(",")
end

In the above example, array is local data and will be released soon
after method is over.

If array is very large, and your method is really long, and you do not
need array after printing, then you can do "array = nil" after its last
use.
HTH.
 
J

John Crichton

Thanks Kumar, I appreciate it and no there was no reason I was using
to_f over to_i other than inexperience.

Thanks again.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top