From: Robert Klemme Date: 2008-02-16T21:24:54+09:00 Subject: Re: Alter String base class to perform new (private methods) before returning itself when called by print statements On 16.02.2008 07:26, Steven G. Harms wrote: > class String > def summon > puts "You summon: " + self > end > def summon2 > puts "You summon: " + self.gsub('x','y') > end > 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. Actually your summon methods do not alter self. > The question is, how can I get `puts "Artax" ` to > produce the same results as `puts "Artax"`. ??? It's the same statement so I would expect the same output (module changes of the instance in between invocations). > They are both Strings > and, as far as I understand it, to_s is what is used to get a String's > display value. It's generally not a good idea to mess with such basic classes like String in this way (i.e. make to_s return something else than self). Since your example does not contain context it's difficult to come up with appropriate suggestions. What are you *really* trying to achieve? > Question #1: Is there a way to references 1 and 2, supra, to do the > same thing? Not sure what you mean here. Can you explain? > Question #2: I thought perhaps I could do the magic on the assignment > operation. I'm not having too much luck with that, as yet. You cannot change the semantics of assignment. You can however define methods that look like assignment, i.e. def foo=(x)...end. I doubt though that this is helpful for you in this context. > If this is the best solution, could the responding individual please > be so gracious as to provide example code of how to override > assignment? I'm muddling about with my re-defined initialize > expecting an optional argument, but I've not figured out how to access > it properly. Again, what problem are you trying to solve? Kind regards robert