From: Jeffrey Schwab Date: 2006-03-02T01:23:37+09:00 Subject: Re: Formatting to "Thousands" Logan Capaldo wrote: > > On Feb 28, 2006, at 11:59 AM, James Edward Gray II wrote: > >> On Feb 28, 2006, at 10:53 AM, Jeffrey Schwab wrote: >> >>> James Edward Gray II wrote: >>> >>>> def commify( number ) >>>> number.to_s.reverse.gsub!(/(\d\d\d)(?=\d)(?!\d*\.)/, '\1,').reverse >>>> end >>> >>> >>> That's nice, except that gsub! returns nil if no substitutions are >>> performed, e.g. if the number has fewer than 4 digits. This can >>> result in an exception like: >>> >>> main.rb:3:in `commify': >>> undefined method `reverse' for nil:NilClass(NoMethodError) >>> >>> Of course, you could just break the chain across multiple lines: >>> >>> def commify(number) >>> s = number.to_s >>> s.reverse! >>> s.gsub!(/(\d\d\d)(?=\d)(?!\d*\.)/, '\1,') >>> s.reverse! >>> end >> >> >> Good catch. I originally had it in multiple lines and I forgot to >> remove the ! when I shortened it for this post. >> >> Thanks. >> >> James Edward Gray II >> >> > > I don't know why but using regexps to do this kind of scares me. Maybe > its cause I don't have as much regexp fu but it just seems like > ruby > ruby > perl > ruby > ruby > > Not that I have anything against perl or regexps, but that particular > regexp seems to scream "I'm doing this with a regexp not because it's > easier but because it's faster and shorter." Not that that's wrong. Hmm > I seem to be trying really hard not to offend anyone :-p. I guess a > rule of thumb for me is more than 1 lookahead assertion and my eyes > glaze over ;) Try the Friedl book. It will open your eyes. :)