From: "Mehr, Assaph (Assaph)" Date: 2004-09-14T13:32:53+09:00 Subject: Re: Recursive Objects (Arrays) in Ruby > 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 > end > > def string=(newString) > @string = newString > mapCharacter > findLeftRight > end > > def mapCharacter > #This method goes through > #each character in .string > #and maps to @characterType > #array. > end > > def findLeftRight > #This method finds and > #assigns @leftSub, @rightSub. > end > > def 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 http://www.ruby-doc.org/core/classes/Module.html#M000715). 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 > end > > Here is the main program: > > test = Formula.new > test.string = "A&B" > test.wff > > Now, Ruby exits with the following complaint: > > in `wff': undefined method `characterType' for # > (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.