From: Brian Candler Date: 2009-01-13T21:13:42+09:00 Subject: Re: extending strftime Lin Wj wrote: > can i change the options which is recognized by strftime > eg: > '%Y %m %d' will apply the format of YYYY mm dd > > can i do something like extending strftime to recognize 'YYYY mm dd' > instead ? > > because right now , i am running the format string which i get(YYYY mm > dd) through a regex and converting them to the parameters which strftime > recognizes That sounds like a perfectly reasonable approach. If you really want to, you can monkey-patch the built-in class (I'd advise against this though, except in small self-contained scripts) class Time alias :old_strftime :strftime STRFMAP = { 'YYYY' => '%Y', 'mm' => '%m', 'dd' => '%d', } STRFRE = /#{STRFMAP.keys.join("|")}/ def strftime(arg) old_strftime(arg.gsub(STRFRE) { STRFMAP[$&] }) end end puts Time.now.strftime("YYYY-mm-dd") Note that by not using the % escape syntax, you may end up with some subtle bugs: puts Time.now.strftime("Today's YYYY-mm-dd, buddy!") # => Today's 2009-01-13, bu13y! You can restrict the regular expression to require a word boundary: STRFRE = /\b(#{STRFMAP.keys.join("|")})\b/ But in this case, a string like "YYYYmmdd" doesn't work. -- Posted via http://www.ruby-forum.com/.