From: David Alan Black Date: 2002-07-23T22:53:50+09:00 Subject: Re: define_method with super in the proc Hi -- On Tue, 23 Jul 2002, Tom Sawyer wrote: > thanks kent, > > well, i'm going to upgrade and try out this alias bit. i was surprised > to find my program working (under a simple test) even without the use of > #super, but it may because it was using the class and not the instance. One thing that may be involved is the fact that super is actually a keyword, not a method. That may have something to do with why it has the effect it does (i.e., being triggered in relation to the method where the proc is defined, instead of being called in the context of the method that's being added). > i'm a bit confused. so let me go into a little more detail and see what > pointers you(s) can give me. > > basically, i have a class with an attribute like so: > > class A > attr_accessor :a > end > > then i subclass it: > > B = Class.new(A) > > i'm not sure if B should be capitalized, perhaps just b? anyway, then i > override #a= in B. > > B.class_eval { define_method(:a=, Proc.new { super; puts a }) > > so the idea for B is to have #a= still set a, but also to print a. Why not the old-fashioned way? class A attr_accessor :a end class B < A def a=(x) super puts @a return @a # #puts returns nil; this is more conventional end end [...] > like i said, right now my program dosen't have the #super and yet it > seems to work. how does that make any sense? Because you're using alias :-) alias is a multi-purpose way of creating a new name for an existing method. super is a specialized case which searches up the class hierarchy for a method of the same name as the one it (super) is used in. So you can, at least theoretically, use alias to mimic super. But in general, the two are quite different. I've found it helpful to think of them as operating along perpendicular axes. alias is horizontal: it creates a new name at the same logical and procedural level as the old name. super is vertical and, as I mentioned, specialized: its job is to bump control up the inheritance chain, based on method name similarity. There have been discussions of this here, which you can track down if interested, some in the context of the question of combining alias and super (which I've never thought was practicable, since they address different needs), and/or in the context of general concern about the safety and cleanness of alias (which I think I do understand, though I really like alias :-) David -- David Alan Black home: dblack@candle.superlink.net work: blackdav@shu.edu Web: http://pirate.shu.edu/~blackdav