On Tuesday 21 August 2001 01:45 pm, Hal wrote: > ----- Original Message ----- > From: Yukihiro Matsumoto <matz / ruby-lang.org> > To: ruby-talk ML <ruby-talk / ruby-lang.org> > Sent: Tuesday, August 21, 2001 9:46 AM > Subject: [ruby-talk:20057] Re: The Ruby Way [was: Ruby Article] > > > But I'm not sure the followings are the Ruby Way: > > |X) Ask objects to convert themselves > But if I understood this statement correctly, I agree with > it. My interpretation was: "If an object is to be converted, > that conversion should not be forced on it from outside > using an external piece of code, but there should be a > method associated with the class or object that enables > this kind of conversion, and that should be used instead." Let's say we have A objects, and B objects that need to be made from the A objects. This means that B has a dependency on A, not the other way around. In, say, C++, the choice would be simple: you wouldn't add a dependency from A to B by adding a conversion method to A. You would make a B constructor that took an A, or you would make a factory method somewhere else that would produce a B given an A. But Ruby allows extension of classes, so we can add behavior to a class from our own modules without touching its source code. So we can add a to_B() method to A without adding a dependency at the source code level. So the C++/Java concerns of adding unnecessary and forbidden knowledge to A are not relevant here, since you can add the A#to_B method without creating a circular dependency. Is this a proper Ruby way to do it? In either case, you would stick to the public interface of the other class, of course. Ruby doesn't allow for overloading on number of arguments (unless I missed something), so providing multiple B constructors that take a variety of arguments (one of which would take an A) would require using different method names: b1 = B.new(1, 'x') # vs. b2 = B.from_A( anA ) I'm assuming that the other alternative (a free factor function running around loose somewhere) would not be "the Ruby way". Which of these is preferred? -- Ned Konz currently: Stanwood, WA email: ned / bike-nomad.com homepage: http://bike-nomad.com