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

···

--
Posted via http://www.ruby-forum.com/.

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

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.

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

Jesus.

···

On Tue, Feb 1, 2011 at 7:11 PM, Jim Carter <jcarter@leupold.com> wrote:

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.