practical use for undef

chalmers picture chalmers · Jan 14, 2011 · Viewed 7.9k times · Source

Possible Duplicate:
undef - Why would you want to undefine a method in ruby?

Can anyone lay out a practical use for undef in ruby? I'm coming from languages like javascript and python that don't have it built in. You could of course simulate it in a language like javascript:

var obj = { func:function(){alert("works")} }
obj.func() // -> "works"
delete(obj["func"])
obj.func() //->obj.func() is not a function

but I've never really had use for that. Are there some common situations where undef is actually useful?

EDIT -- Just came across this in the book "The Ruby Programming Language":

Another technique to prevent copying of objects is to use undef to simply remove the clone and dup methods. Yet another approach is to redefine the clone and dup methods so that they raise an exception with an error message that specifically says that copies are not permitted. Such an error message might be helpful to programmers who are using your class.

Answer

noodl picture noodl · Jan 14, 2011

I can only say that I've never had a use for it in 5 years. Perhaps more usefully, grepping through the entire source of rails shows only 7 instances and they're all meta-programming related. (undef_method has rather more instances at 22). It appears to be useful for testing the behaviour of classes with and without modules mixed-in.

Hopefully someone can point out some more conventional uses for it.

EDIT See this previous question: undef - Why would you want to undefine a method in ruby?