From: Trans Date: 2008-09-09T10:29:23+09:00 Subject: Re: #to_self On Sep 8, 6:21 pm, Nobuyoshi Nakada wrote: > Hi, > > At Mon, 8 Sep 2008 00:35:34 +0900, > Trans wrote in [ruby-talk:314145]: > > > That could work, but if to_self is used there will be issues clearly > > (!!!!!!!!! ain't a number). Hence, what I'm really after is an > > optional method that can be defined when needed to say "how to become > > grumpy". Then: > > Why not just override Symbol#grumpy? > >   module Grumpy >     def grumpize >       "#{to_s.upcase}!!!!!!!!!" >     end >   end > >   class String >     include Grumpy >   end > >   class Symbol >     include Grumpy >     def grumpize >       super.to_sym >     end >   end > >   p "fun".grumpize  #=> "FUN!!!!!!!!!" >   p :fun.grumpize  #=> :"FUN!!!!!!!!!" Easy enough when you have one method. No fun with 20+. > Or, String#try_convert is defined in 1.9: > >   module Grumpy >     def grumpize >       self.class.try_convert("#{to_s.upcase}!!!!!!!!!") >     end >   end > >   class String >     include Grumpy >   end > >   class Symbol >     include Grumpy >     def self.try_convert(s) >       s.to_sym >     end >   end > >   p "fun".grumpize  #=> "FUN!!!!!!!!!" >   p :fun.grumpize  #=> :"FUN!!!!!!!!!" Ah, now that's interesting, and more along the lines of what I've been pondering. This is like #to_self defined on the metaclass, which makes sense. And is perfect use if limited to particular conversions (like String/Symbol conversion). What is the intended purpose of #try_convert, BTW, ie. Why was it added to 1.9? My case still calls for a special method though, if it is to be open for use for anything more than String/Symbol. The Integer example for instance --a try_convert of #to_i here would be pointless for Grumpies. The use of the special method is basically the same concept as for Hash#<< on ruby-core where Enumerable could use an optional enumerator/species method. Seems almost like some sort of Design Pattern. T.