To count the number of spaces at the beginning and end of line s , I do:
s
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?
another version, it should be as small as possible
s[/\A */].size s[/ *\z/].size
You can do it right away:
_, spaces_at_beginning, spaces_at_end = /^( *).*?( *)$/.match(s).to_a.map(&:length)
Definitely not more elegant though.
I don't know if this is more efficient, but it works too.
s.count(' ') - s.lstrip.count(' ') s.count(' ') - s.rstrip.count(' ')
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)
It is also easy to do:
beginning = s.length - s.lstrip.length ending = s.length - s.rstrip.length