As a disclaimer, I'm new to object-oriented programming and to Ruby;
so
I'm not sure if I'm even describing this problem correctly. Here goes:
I have an object called "formula" which has properties .string (the
original formula), .leftSub, .rightSub (left and right subformula of
the original formula) and .characterType (an array identifying each
character in .string as being a particular type - e.g., number,
letter,
and so on).
Now, I have the following:
class Formula
def initialize
@string = nil
@leftSub = nil
@rightSub = nil
@characterType = Array.new
enddef string=(newString)
@string = newString
mapCharacter
findLeftRight
enddef mapCharacter
#This method goes through
#each character in .string
#and maps to @characterType
#array.
enddef findLeftRight
#This method finds and
#assigns @leftSub, @rightSub.
enddef wff
testFormula1 = Formula.new
testFormula2 = Formula.new
testFormula1.string = @leftSub
testFormula2.string = @rightSub#Problem line:
puts testFormula1.characterType[0]
You can not access the (private) member directly in this manner.
Consider adding an accessor for it (e.g. attr_accessor; see
class Module - RDoc Documentation).
You probably come from class-oriented programming ala c++ and assumed
that you can access another object's private member variables, as long
as both are of the same class. In Ruby, all member variables are private
to that object only. You can add protected accessors that will simulate
the behaviour you're looking for (if I understand your code correctly).
Read the section "Objects and Attributes" in:
http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_classes.html
HTH,
Assaph
ยทยทยท
end
endHere is the main program:
test = Formula.new
test.string = "A&B"
test.wffNow, Ruby exits with the following complaint:
in `wff': undefined method `characterType' for #<Formula:0xbceb0>
(NameError)It is as if I am not referring to the element of the array correctly;
but I can't figure out exactly how I should be referring to it. Any
help would be appreciated.