From: Jim Cochrane Date: 2006-11-27T03:30:09+09:00 Subject: Re: coding practise On 2006-11-26, sempsteen wrote: > Yep, now i know that my Hash example is a different matter. > >> The fix: >> change 'has_answer' to store the answer (privately) after calculating it and >> 'answer' to simply retrieve that answer if it has been created. > > Where do you suggest to store the value for my amicable numbers example? Looks like Paul has given you the answer (which I appreciate, since I don't have the time to give a good answer). > > class Fixnum > def has_friend? > t1, t2 = 1, 1 > 2.upto(self / 2) {|i| t1 += i if self % i == 0} > 2.upto(t1 / 2) {|i| t2 += i if t1 % i == 0} > return self == t2 && self != t1 > end > def friend > t1, t2 = 1, 1 > 2.upto(self / 2) {|i| t1 += i if self % i == 0} > 2.upto(t1 / 2) {|i| t2 += i if t1 % i == 0} > return t1 if self == t2 && self != t1 > end > end > > 1.upto(1000) {|i| print i, "\t<->\t", i.friend, "\n" if i.has_friend?} > > I want a "has_friend?" method and "friend" method. One for searching > for the existing of given number, other one is for getting the value > of the friend of that number. And i want those methods inside "Fixnum" > class structure, like as instance methods. > when i call has_friend? method it will store its value to some kind of > variable, but return true or false and, when i call friend method it > will get the stored value. > But what must be that some kind of variable that holds the value? > - class variable > - instance variable > - global > - or what? > --