Question

I have a ruby script in which I would like to encapsulate variable initialization/reset in a method. I created the below method for variable resetting. But in irb, this method runs fine but when I print the variables after running the method like this: initer. It didnt do the job.

def intiter
  cntr = 0
  rec = 0
  timer = 0
end
Was it helpful?

Solution

Your method only sets local variables within the scope of initer; when that method ends, those variables that you set to 0 disappear into the ether. You need to be referencing class, instance, or global variables in order to set them from within your method. Class variables begin with @@ and are shared by all instances of that class; instance variables begin with @ and are accessible by anything within a particular instance of a class; globals begin with $ and can be used from anywhere in the program, but can be subject to unexpected changes. Without knowing more code and what your overall design is, there's not much more I can help you with.

Edit: previous link I included wasn't to the correct section. Try http://docs.ruby-doc.com/docs/ProgrammingRuby/html/tut_classes.html for more.

Also, why's (poignant) guide to ruby is good... if it's your cup of tea, anyway. I like it.

OTHER TIPS

The def keyword begins a new scope, which means that any variables defined here are brand new and will be destroyed when the end keyword is hit. You are creating a brand new copy of those variables, setting them to 0, then destroying them. The original variables are never touched.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top