开发者

practical use for undef [duplicate]

This question already has answers here: Closed 12 years ago.

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 cl开发者_如何学JAVAone 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.


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?


Blocking a child class from calling a method defined in the superclass (this is actually used in mongrel's setup.rb) (paraphrasing):

class Item
  def set
    do_something
  end
end

class ExecItem < Item
  undef set
end

Though I guess undef_method would have the same effect.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜