Variables and scope

Hi all,

I would be asking my instructor this question be she is not available
on
the weekends…

How do I make “n” available from anywhere inside the class? I need to
keep the values in n from call to call.

When calling the method “pt”, “n” acts as if it was not declared above.

I get -1 instead of what I wish for … 99.

Thanks in advance,

Mike

class Test
n=100

def pt
puts “hi there”
n=-1
end

end

t = Test.new
puts t.pt

take note of the usage of @ for scope as well as the special
initialize method used as a constructor for the object.

also note note you common bug/mistake. Your where setting n to
negative one. you need to use n = n + -1 or shorthand version below is
n += -1

class Test
def initialize
@n = 100
end

def pt
p “hi there”
@n += -1
end
end

t = Test.new
puts t.pt

If you would like to know more have a look at attr_* in ruby

Good luck with your classes

~Stu

You are getting a -1 because you are using local variables. Thus, the n
within your def is not the same as the n within your class.
Since you declared n to be -1 in your def, that is what your program
responded with, a -1.
You need to initialize an instance variable that will be available
throughout the class.

You can also make your code more utilitarian with a parameter value that
can be changed any time you create a new instance.
Try the following:

class Test

def initialize(n)
@n = n
end

def pt
puts “hi there”
@n -= 1
end
end

t = Test.new(100)
puts t.pt

This way, you are not tied down to the value 100, but can use any value
you want.
I am new at this game and just taking the baby steps, but this seemed to
work.

Lauren

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs