variables and scope

M

Mike 1.

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
 
S

Stu

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 =3D n + -1 or shorthand version below is
n +=3D -1

class Test
def initialize
@n =3D 100
end

def pt
p "hi there"
@n +=3D -1
end
end

t =3D 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
 
L

Lauren Buckland

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 =3D n
end

def pt
puts "hi there"
@n -=3D 1
end
end

t =3D 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



take note of the usage of @ for scope as well as the special
initialize method used as a constructor for the object.
=20
also note note you common bug/mistake. Your where setting n to
negative one. you need to use n =3D n + -1 or shorthand version below = is
n +=3D -1
=20
class Test
def initialize
@n =3D 100
end
=20
def pt
p "hi there"
@n +=3D -1
end
end
=20
t =3D Test.new
puts t.pt
=20
If you would like to know more have a look at attr_* in ruby
=20
Good luck with your classes
=20
~Stu
=20
=20
 

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,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top