Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

To count the number of spaces at the beginning and end of string 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 only to be handled separately.

Is there a better (more elegant / efficient) method to do so?

like image 940
Misha Moroshko Avatar asked May 04 '12 11:05

Misha Moroshko


3 Answers

s.split(s.strip).first.size
s.split(s.strip).last.size

you could also do

beginning_spaces_length , ending_spaces_length = s.split(s.strip).map(&:size) 
like image 57
peter Avatar answered Oct 24 '22 05:10

peter


You could do it at once:

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

Definitely not more elegant though.

like image 43
Mladen Jablanović Avatar answered Oct 24 '22 03:10

Mladen Jablanović


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

s.count(' ') - s.lstrip.count(' ')
s.count(' ') - s.rstrip.count(' ')
like image 20
Subodh Avatar answered Oct 24 '22 05:10

Subodh