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) ?
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.