From: Steve Tuckner Date: 2002-09-14T04:46:46+09:00 Subject: RE: General ?s about a couple of Ruby features The biggest reason I can think of for modifying existing classes is to enhance the built in classes in ruby. If you don't like the way the Hash class gets initalized and you want to have a block run to generate the default value for a new hash entry, then you can do the following: class << Hash alias :old_new :new def new(default = nil, &block) a = old_new(default) if block_given? raise "Invalid call" if default a.instance_eval <<-EOT @block = block alias :aref :[] def [](a) if ! has_key?a self[a] = @block[] end aref(a) end EOT end a end end Thanks for the above code to some ruby-talk volunteer long ago... Also if you want to add to the string class a new member function that logically belongs in the string class like a new kind of gsub where the pre-match and post matches are passed in and possibly modified (like below): # this version of gsub requires a block as an argument # if the value returned from the block is a string # the matched sub-string is replaced with a string # if the value returned is an array of 2 elements # the data before the match is replaced by array[0] # the matched sub-string is replaced by array[1] # if the value returned is an array of 3 elements # the data before the match is replaced by array[0] # the matched sub-string is replaced by array[1] # the data after the match is replaced by array[2] def gsub2(re) sin = self.dup sout = "" while sin.length > 0 m = re.match(sin) if m then r = yield m if r.kind_of?(Array) then if (r.length >= 2 && r.length <= 3) then sout << r[0] + r[1] else throw "gsub2: array returned is not of length 2 or 3" end else sout << m.pre_match + r end if r.kind_of?(Array) && r.length == 3 then sin = r[2] else sin = m.post_match end else sout << sin break end end sout end end I have a directory of "my" files, (myhash.rb, mystring.rb) just to have my own extensions to existing ruby classes. In other languages without open classes, these modifications would have to be in subclasses or as standalone functions. Steve Tuckner -----Original Message----- From: Chris Morris [mailto:chrismo@clabs.org] Sent: Friday, September 13, 2002 2:29 PM To: ruby-talk@ruby-lang.org Subject: Re: General ?s about a couple of Ruby features > Modifying class A is useful when: > a) there is a bug in class A and we want to fix the bug without > shutting down the application. > b) class A is missing a method that a method in class B needs to have > defined in order to accept an object of class A as a parameter. > c) for creating delegate objects (objects that intercept method calls > and pass them onto another object) without using method_missing. It's also handy because it allows you to break out your class and module code into different files if necessary. This is more common perhaps using modules for namespaces. If I have 12 classes in 12 files, but want them all in the same module/namespace, no problem. Chris