ASPN ActiveState Programmer Network
ActiveState
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups


Recent Messages
List Archives
About the List
List Leaders
Subscription Options

View Subscriptions
Help

View by Topic
ActiveState
.NET Framework
Open Source
Perl
PHP
Python
Tcl
Web Services
XML & XSLT

View by Category
Database
General
SOAP
System Administration
Tools
User Interfaces
Web Programming
XML Programming


MyASPN >> Mail Archive >> ruby-talk
ruby-talk
Difference between define_method and def method; end
by Rune Hammersland other posts by this author
Oct 31 2006 3:38AM messages near this date
Re: Ruby tools for managing static websites? | Re: Difference between define_method and def method; end
Hello dear Rubyists.

It was suggested on the IRC channel that I try the ML for this  
problem ...

While looking at how to undefine a method, I found out that there is  
a difference in how define_method and the def ... end block works.  
Example coming up:

# Two classes to play with.
class Parent
     def lol
         puts "P: LOL"
     end
end

class Child < Parent
     # Commenting out the redefinition doesn't help
     def lol
         puts "C: LOL"
     end
end

# test1.rb
c = Child.new
c.lol # =>  "C: LOL" or "P: LOL" if commented out
Child.class_eval { undef_method :lol }

# Try to redefine method and call super.
class Child < Parent
     def lol
         print "LOL: "
         begin
             super
         rescue NameError =>  e
             puts e.to_s
         end
     end
end

c.lol # =>  "LOL: superclass method `lol' disabled"

# Then in test2.rb:

c = Child.new
c.lol # =>  "C: LOL", or "P: LOL" if commented out.

Child.class_eval { undef_method :lol }
# Try to redefine method and call super.
Child.class_eval do
     define_method(:lol) { print "LOL: "; super }
end
c.lol # =>  "LOL: P: LOL"

Now ... Why can I call super in the redefinition of the method using  
define_method, and not using the def ... end block? For me this seems  
like an inconsistency. First I thought it was neat that I could not  
call super in the method after using undef_method and redefining it  
again, but then I found out I could using define_method.

As the comments state, I also tried to run the code with the  
redefinition of the lol method in the Child class, but to no help.  
The output is roughly the same (P instead of C obviously).

Anybody care to shed a little light on this?

-- 
Vennlig Hilsen
Rune Hammersland
Thread:
Rune Hammersland
Ara T Howard
Robert Dober
Ara T Howard
Rune Hammersland
Robert Dober
Rune Hammersland
Rune Hammersland
Timothy Goddard

Privacy Policy | Email Opt-out | Feedback | Syndication
© ActiveState Software Inc. All rights reserved