From: matt@... (matt neuburg) Date: 2009-04-03T13:04:39+09:00 Subject: Re: Class in a Class problem wrote: > My intent is to create a class that has access to call a method in an > instantiation of another class > > However my knowledge of Ruby classes (Ok classes in general) is > somewhat lacking > > The example below is a LOT simplified But I need class B to call a > method within an instantiation of class A's. > > one alternative is to seperate the classes and then just do "b=B.new > (a)" but I think that looks really messy and > - I have then to check a bunch of stuff about the parameter a > - I would have a world of more hurt trying to ensure that only one B > instantiation pointed to each a > > Can anyone help? Or tell me that I am doing this all wrong. > > > Paul > > ----- > > class A > class B > def initialize() > puts "b init" > print_stuff() > end > end > > def B > return B > end > > def print_stuff() > puts "here" > end > end > > a = A.new() > b = a.B.new() Maybe I'm reading your question wrong, but the concept "has access to call" is misleading, it seems to me, since there is never lack of access in Ruby. So what you're really asking, I'm guessing, is that when a B instance is produced by an A instance, it should point to that A instance. We can do that without even giving the B class a name: class A def b Class.new do def initialize(a) @a = a end attr :a end.new(self) end # other stuff that an A knows how to do end So now you say: a = A.new b = a.b puts (b.a == a) #=> true So we see that b's a is indeed pointing at the correct instance. So now you can say b.a.print_stuff or anything else you like. Is that the spirit of what you're after? m. -- matt neuburg, phd = matt@tidbits.com, http://www.tidbits.com/matt/ Leopard - http://www.takecontrolbooks.com/leopard-customizing.html AppleScript - http://www.amazon.com/gp/product/0596102119 Read TidBITS! It's free and smart. http://www.tidbits.com