General Ruby Object Oriented

I’m a newbie to Ruby (hmm… rhymes) and to object oriented programming
in general, so having a hard time wrapping my mind around a paradigm
which differs from C language. Here is a short snippet of code, the
general flow coming from the book “The Ruby Way” (pg 392).

The class ExternalBallistics would be the equivalent of my top level
function (or container of functions) which will get inputs from the Main
(in this case rails text and selection box fields) and will calculate a
series of results.

desktop is supposed to define those variables, which ExternalBallistics
can then apply to its various methods. However, it is not working out
that way. Ruby is complaining that the variables a, b and c are not
defined. Note that the relationship between ExternalBallistics and
BasicMath is OK, but the relationship between desktop and
ExternalBallistics is not, as if I am not using the attributes
incorrectly. Can someone help me here.

class BasicMath

Could be called as a class, static, method

attr_accessor :a, :b, :c

def add(a, b, c)
m = (a + b - c)/b
n = a + b
return m, n
end

def calc_nrows(a, b, c)
nrows = (a - b)/c
return nrows.round
end

end

class ExternalBallistics

attr_accessor :a,:b,:c

def initialize(&block)
instance eval &block
end

tc = BasicMath.new
puts tc.add(a,b,c)
puts tc.calc_nrows(5.0,3.0,1.0)

end

desktop = ExternalBallistics.new do
self.a = 5.0
self.b = 3.0
self.c = 1.0

end

On Tue, Jan 25, 2011 at 12:33 PM, Jim C. [email protected]
wrote:

def initialize(&block)
instance eval &block
end

This should be instance_eval (with an underscore)

tc = BasicMath.new
puts tc.add(a,b,c)
puts tc.calc_nrows(5.0,3.0,1.0)

This code is inside your class definition. So, at that time, self is
that
class, not an instance of that class. How about wrapping it in a method
called calculate, so that its instances can call that code by invoking
the
calculate method:
def calculate
tc = BasicMath.new
puts tc.add(a,b,c)
puts tc.calc_nrows(5.0,3.0,1.0)
end

desktop = ExternalBallistics.new do

self.a = 5.0
self.b = 3.0
self.c = 1.0
end

Then we would just need to stick a call to calculate in the block:

desktop = ExternalBallistics.new do
self.a = 5.0
self.b = 3.0
self.c = 1.0
calculate
end

On Tue, Jan 25, 2011 at 12:54 PM, Jim C. [email protected]
wrote:

but I don’t understand the authors assignment of self.a, self.b, self.c,
especially in light of the fact that it doesn’t work. If anyone can
share any insight, I’d appreciate it.

In ExternalBallistics#initialize, you instance_eval the block. That sets
self to be the instance that is created when you do
ExternalBallistics.new,
so when you are in the block and say self.a=5.0, you are telling it to
invoke the method a= and pass it the value 5.0

Awesome! That did the trick. Thanks

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