From: Rick DeNatale Date: 2007-10-11T21:48:09+09:00 Subject: Re: will #in? be in ruby2? (was Re: Finding shared elements between to arrays.) On 10/11/07, Robert Klemme wrote: > While reading this thread another possible solution came to my mind: > what about an operator like "def_once" or "def!" which will raise an > exception if the method is defined for that class already? Of course, > we could cook our own using define_method but there are some > restrictions so it's not exactly equivalent to def. > > Semantics would have to be carefully chosen. At the moment it seems > that "def_once" should raise only if a) the instance's class has an > instance method of the same name already or b) there is a singleton > method of the same name. However, I am not sure how to deal with the > situation when there is an instance method in the class and then a > singleton method definition is attempted. Jim Weirich uses something like this in rake. He defines a method which takes a block containing a method definition class Module # Check for an existing method in the current class before extending. IF # the method already exists, then a warning is printed and the extension is # not added. Otherwise the block is yielded and any definitions in the # block will take effect. # # Usage: # # class String # rake_extension("xyz") do # def xyz # ... # end # end # end # def rake_extension(method) if instance_methods.include?(method) $stderr.puts "WARNING: Possible conflict with Rake extension: #{self}##{method} already exists" else yield end end end Note that it produces a warning rather than an exception. Also I guess he figured that Module#rake_extension wouldn't already exist! It pays to read the classics! -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/