From: "David A. Black" Date: 2008-09-10T07:38:00+09:00 Subject: Re: How to access a method in the parent class --1926193751-957717402-1221000265=:12029 Content-Type: MULTIPART/MIXED; BOUNDARY="1926193751-957717402-1221000265=:12029" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --1926193751-957717402-1221000265=:12029 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Wed, 10 Sep 2008, James Coglan wrote: > 2008/9/9 I=F1aki Baz Castillo > >> Hi, I'll explain my problem with an example code: >> >> ----------------------- >> module M >> def hello >> puts "hello !!!" >> B.new >> end >> >> class B >> def initialize >> puts "B instance initialized !!!" >> bye() <--- ERROR !!!! >> end >> end >> end >> >> >> class A >> include M >> >> def bye >> puts "bye !!!" >> end >> end >> >> >> a =3D A.new >> a.hello >> ----------------------- >> >> >> I want the following behaviour: >> >> irb> a.hello >> =3D> "hello !!!" >> =3D> "B instance initialized !!!" >> =3D> "bye !!!" >> >> >> But the last bye() gives an error since, of course, "bye" is not defined= in >> B >> class, but in A class. >> >> I know that if it would be: >> ------------------ >> module M >> >> def hello >> puts "hello !!!" >> bye >> end >> >> end >> >> irb> a.hellp >> ------------------ >> This works since "bye()" calls the "bye" method in class A. But this is = not >> my >> case. >> >> How could I call A#bye method from M::B class? >> >> Thanks a lot. >> > > > To call a method from another class in the context of an instance of B, p= ut > this inside M::B#initialize: > > A.instance_method(:bye).bind(self).call() That won't work here, because you'd need an instance of A (or a subclass of A). > Hard to tell from this code, seeing as how it does nothing apparently > useful, but if you find yourself doing this it may be a sign that you nee= d > to rethink your design. It definitely looks a bit inside-out: A requires that M exist, but A is essentially trying to serve as a superclass for M::B. Sort of like this: module M def hello puts "hello !!!" B.new end end class A include M def bye puts "bye !!!" end end module M class B < A def initialize puts "B instance initialized !!!" bye end end end which works, but does indeed look like it would need some ironing out in the design. David --=20 Rails training from David A. Black and Ruby Power and Light: Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL Advancing with Rails January 19-22 Fort Lauderdale, FL * * Co-taught with Patrick Ewing! See http://www.rubypal.com for details and updates! --1926193751-957717402-1221000265=:12029-- --1926193751-957717402-1221000265=:12029--