attr_reader - general question

J

Jim Carter

I have the following configuration:

class ExternalBallistics

attr_accessor :a,:b #inputs
attr_reader :c #outputs

def initialize(&block)
instance_eval &block
end

def calculate
c = a + b
end

end #class



ExternalBallistics.new do

self.a = 5
self.b = 3

calculate

puts self.c

end #ExternalBallistics


This returns a nil value for c. If I use "puts" inside of def
calculate, I will get 8 for an answer. Why does a and b act globally
and c not. Am I forced to use a return on calculate to get an answer.
If I do so, do I still need to define an attr_reader :c (what use is it
then) ?


Thanks
 
J

Jesús Gabriel y Galán

I have the following configuration:

class ExternalBallistics

=A0 =A0attr_accessor =A0 =A0:a,:b =A0 #inputs
=A0 =A0attr_reader =A0 =A0 =A0:c =A0 =A0 =A0#outputs

=A0 =A0def initialize(&block)
=A0 =A0 instance_eval &block
=A0 =A0end

=A0 =A0def calculate
=A0 =A0 =A0 c =3D a + b

This is not calling the method "c=3D", not that you have one, in any
case. "c" is considered a local variable.
Change it to:

@c =3D a + b

to set the value in the instance variable that your reader will access.
=A0 =A0end

end #class



ExternalBallistics.new do

=A0 self.a =3D 5
=A0 self.b =3D 3

=A0 calculate

=A0 puts self.c

end #ExternalBallistics


This returns a nil value for c. =A0If I use "puts" inside of def
calculate, I will get 8 for an answer. =A0Why does a and b act globally
and c not. =A0Am I forced to use a return on calculate to get an answer.
If I do so, do I still need to define an attr_reader :c (what use is it
then) ?


Thanks

Jesus.
 
S

Steve Klabnik

[Note: parts of this message were removed to make it a legal post.]
Am I forced to use a return on calculate to get an answer.

nope, if you 'puts calcluate' you should see 8. If you want to assign to c,
you should use self.c = ... though. And if you're assigning to c, you should
use attr_accessor on it to get a c= method as well.
 

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,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top