From: Trans Date: 2008-03-02T23:12:26+09:00 Subject: Re: Named sprintf parameters On Feb 28, 3:42 pm, "Adam Shelly" wrote: > 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 Looks like you get the prize ;) I would like to add this to Facets, though under a slightly different naming of course. Not sure what though #printfv #sprintfv ? Thanks! T.