From: Adam Shelly Date: 2008-02-29T05:42:26+09:00 Subject: Re: Named sprintf parameters On 2/28/08, yermej wrote: > On Feb 28, 11:29 am, ara howard wrote: > > > class String > > module M > > def % *args > > newstuff > > super > > end > > end > > include M > > end > > > > However, when I try anything like that, it only calls the original > method. The method defined inside of M isn't called. ... > I also couldn't get Ara's example to work, so I resorted to monkeypatching. (Yes, I know, I am Destroying Ruby..) ---------- p "I am %s." % "string" p "I am %s." % ["array"] p "I am %s." % { :name => "hash" } begin p "I am %(name)s." % { :name => "hash" } rescue ArgumentError => err p "caught #{err}" end puts "\nMonkeyPatching!\n\n" class String alias :old_percent :% def % arg arr = (arg.kind_of? Array) ? arg : [arg] target = self.gsub(/%\((.+?)\)/){|m| raise ArgumentError, "named parameters need hash" unless arg.kind_of? Hash arr << arg[$1.to_sym] "%#{arr.size}$" } target.old_percent arr end end p "I am %s." % "string" p "I am %s." % ["array"] p "I am %s." % { :name => "hash" } p "I am %(name)s." % { :name => "hash" } p "I am %(name)s %(with)s %(what)s"%{:what => "multiple arguments", :with => "including", :name=> 'hash'} p "I am %(name)s %(with)s %1$p"%{:with => "containing", :name=> 'hash'} p "I am %(name)s." % [:name, "array"] -Adam P.S. It actually looks like patching sprintf wouldn't be too hard, as long as you disallowed mixing named arguments with any other type.