Ruby: How to count the number of spaces at the beginning and end of a line?

To count the number of spaces at the beginning and end of line s , I do:

 s.index(/[^ ]/) # Number of spaces at the beginning of s s.reverse.index(/[^ ]/) # Number of spaces at the end of s 

This approach requires the edge case when s contains spaces that are processed separately.

Is there a better (more elegant / efficient) way to do this?

+7
source share
5 answers

another version, it should be as small as possible

 s[/\A */].size s[/ *\z/].size 
+12
source

You can do it right away:

 _, spaces_at_beginning, spaces_at_end = /^( *).*?( *)$/.match(s).to_a.map(&:length) 

Definitely not more elegant though.

+3
source

I don't know if this is more efficient, but it works too.

 s.count(' ') - s.lstrip.count(' ') s.count(' ') - s.rstrip.count(' ') 
+2
source
 s.split(s.strip).first.size s.split(s.strip).last.size 

you can also do

 beginning_spaces_length , ending_spaces_length = s.split(s.strip).map(&:size) 
+1
source

It is also easy to do:

 beginning = s.length - s.lstrip.length ending = s.length - s.rstrip.length 
0
source

All Articles