From: Colin Bartlett Date: 2010-03-31T01:22:35+09:00 Subject: Re: return number of spaces at the beginning of a line On Tue, Mar 30, 2010 at 4:35 PM, Robert Klemme wrote: > I think I have to hurry: rain radar indicates showers coming my way. From the west? > 2010/3/30 Colin Bartlett : >> How about this? I think it's different from the other solutions(?), >> it seems to work, and it doesn't create a string object(?). >>  (str =~ /[^ ]/) || str.length > > I'm afraid, that is not correct; the String is created as a side > effect and stored in a global variable: > > irb(main):001:0> str = "   foo" #=> "   foo" > irb(main):002:0> str =~ /[^ ]/ #=> 3 > irb(main):003:0> $& #=> "f" > > And it has the disadvantage over str[/\A */].length that likely is > slower because of the alternative. I'm glad that my (mathematically trained!) caution decided to add that "(?)". I nearly didn't put it in, but had second thoughts! I'd forgotten about the global variables. I see that str.index( regexp ) also sets $&, which is nice to be reminded of, first because it might come in handy, and second because, as you point out, side effects might make what appears to be an "elegant" solution not elegant. Well, one learns from ones mistakes!