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

count, ruby, space, string

Solution

another version, this must be the shortest possible

s[/\A */].size
s[/ *\z/].size

Problem

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?

Original source