Frykholm, Niklas wrote:


> With this modification you can do this. h.upcase in String does not
> return a String, it returns an object of the same type as h (in
> this case a HoX). This is what makes it possible to chain calls in
> this way.
> 
> Your class, HoX should be as polite, that is why delete_digits
> should use self.class.new rather than HoX.new, it makes it possible
> for someone to create a subclass of HoX and chain the method
> calls.


Here is the new version, thanks a lot.

But I have a new question:

--file begin--

class HoX < String

   def delete_digits
     self.class.new self.gsub /\d/,''
   end

   def repeat
     self.class.new self.dup * 2
   end

   def all
     delete_digits.repeat
   end

end

h = HoX.new 'a1b1c1'

# works, because h.upcase returns a HoX
intermingled01 = h.repeat.upcase.delete_digits
puts intermingled01 # -> ABCABC

# doesn't work, because h.reverse returns a String
# intermingled02 = h.repeat.reverse.delete_digits
# puts intermingled02 # -> ~ "undefined method 'delete_digits' for 
"...":String"

# (it works in this sequence)
# intermingled03 = h.repeat.delete_digits.reverse
# puts intermingled03 # -> cbacba
# but only because there's no call to a HoX method after .reverse

# If all methods of class String would return objects of the type of the 
receiver
# like upcase does, method calls could be intermingled freely, in any 
sequence.
--file end--


Tobi

-- 
Tobias Reif
http://www.pinkjuice.com/myDigitalProfile.xhtml

go_to('www.ruby-lang.org').get(ruby).play.create.have_fun
http://www.pinkjuice.com/ruby/