From: Todd Benson Date: 2008-02-16T22:36:59+09:00 Subject: Re: Alter String base class to perform new (private methods) before returning itself when called by print statements On Feb 16, 2008 12:29 AM, Steven G. Harms wrote: > class String > def summon > puts "You summon: " + self > end > def summon2 > puts "You summon: " + self.gsub('x','y') > end Keep in mind that these methods output what you want in irb, but return nil. In my irb session it looks something like this... irb(main):001:0> class String irb(main):002:1> def summon irb(main):003:2> puts "You summon: " + self irb(main):004:2> end irb(main):005:1> end => nil irb(main):006:0> s = "hello".summon You summon: hello => nil irb(main):007:0> s => nil > def to_s > return "Atreyu" > end > end > > "Artax".summon > "Artax".summon2 > > puts "Artax".to_s # reference 1 > puts "Artax" # reference 2 > > This produces... > > You summon: Artax > You summon: Artay > Atreyu > Artax > > Now the "summon" methods indicate to me that by referencing self in > methods added to the String class, you can alter the string from > within itself. Yes, this is possible. > The question is, how can I get `puts "Artax" ` to > produce the same results as `puts "Artax"`. They are both Strings > and, as far as I understand it, to_s is what is used to get a String's > display value. > > Question #1: Is there a way to references 1 and 2, supra, to do the > same thing? Look at these two (using the previous code)... puts s.to_s puts(s).to_s > > Thanks, > > Steven Todd