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

Ruby:如何计算字符串开头和结尾的空格数?,ruby,string,count,space,Ruby,String,Count,Space,要计算字符串sI开头和结尾的空格数,请执行以下操作: s.index(/[^ ]/) # Number of spaces at the beginning of s s.reverse.index(/[^ ]/) # Number of spaces at the end of s 当s仅包含要单独处理的空格时,此方法需要使用边大小写 有没有更好(更优雅/更高效)的方法可以做到这一点?您可以立即做到: _, spaces_at_beginning, spa

要计算字符串
s
I开头和结尾的空格数,请执行以下操作:

s.index(/[^ ]/)              # Number of spaces at the beginning of s
s.reverse.index(/[^ ]/)      # Number of spaces at the end of s
s
仅包含要单独处理的空格时,此方法需要使用边大小写


有没有更好(更优雅/更高效)的方法可以做到这一点?

您可以立即做到:

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

当然不会更优雅。

我不知道它是否更高效,但这也很有效

s.count(' ') - s.lstrip.count(' ')
s.count(' ') - s.rstrip.count(' ')
这也很容易做到:

beginning =  s.length - s.lstrip.length
ending = s.length - s.rstrip.length
你也可以这样做

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

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

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

如果
s
包含其他空格,例如
s=“\tx”
\t
计算为单个空格,则此方法将不起作用。然而,也许我还不明白你的意思;您希望如何处理制表符大小写?
\t
应被视为任何其他字符。问题是关于计算空格。很抱歉,我没有正确理解您的问题:)对于“aa”或空字符串之类的情况,最好使用
*
而不是
+
s[/\A */].size
s[/ *\z/].size