文字列の最初と最後のスペースの数を数えるには、次のs
ようにします。
s.index(/[^ ]/) # Number of spaces at the beginning of s
s.reverse.index(/[^ ]/) # Number of spaces at the end of s
このアプローチでは、s
スペースが含まれている場合はエッジケースが必要であり、個別に処理する必要があります。
そうするためのより良い(よりエレガントで効率的な)方法はありますか?