Attr_reader - general question

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

On Tue, Feb 1, 2011 at 7:11 PM, Jim C. [email protected] wrote:

def calculate
c = a + b

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

@c = a + b

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

If I do so, do I still need to define an attr_reader :c (what use is it
then) ?

Thanks

Jesus.

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.

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