LoginSignup
4
1

More than 3 years have passed since last update.

【Ruby】String#split で区切り文字が末尾にあるときの注意点

Posted at

RubyのString#splitで区切り文字が末尾にある場合、デフォルトでは戻り値の配列は末尾要素に空文字列を含みません

どういうことかというと、

'a..b.c'.split('.')
# => ["a", "", "b", "c"]

このように、区切り文字が連続する場合には空文字列を要素として含むにもかかわらず、

'a.b.c.'.split('.')
# => ["a", "b", "c"]

末尾に区切り文字がある場合は空文字列を要素として含んでくれないのです。

解決策

String#splitメソッドには実は第2引数があり、ここに負数を指定することで解決できます。

'a.b.c.'.split('.', -1)
# => ["a", "b", "c", ""]

ちなみに

先頭に区切り文字がある場合は、デフォルトでも先頭要素に空文字列のある配列を返してくれます

'.a.b.c'.split('.')
# => ["", "a", "b", "c"]

バージョン情報

Ruby: 2.6.3

参考

4
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
1