Ruby:如何计算字符串开头和结尾的空格数?

Mis*_*hko 8 ruby string space count

要计算字符串开头和结尾的空格数,s我会这样做:

s.index(/[^ ]/)              # Number of spaces at the beginning of s
s.reverse.index(/[^ ]/)      # Number of spaces at the end of s
Run Code Online (Sandbox Code Playgroud)

s包含空格时,这种方法需要边缘情况才能单独处理.

是否有更好(更优雅/更有效)的方法呢?

pet*_*ter 13

另一个版本,这必须是最短的

s[/\A */].size
s[/ *\z/].size
Run Code Online (Sandbox Code Playgroud)