LoginSignup
2
0

More than 3 years have passed since last update.

[Ruby] String#split でセパレータも結果に含める

Last updated at Posted at 2019-05-08

問題

'mono,di,tri'.split(',') #=> ["mono", "di", "tri"]

この結果を ["mono", ",", "di", ",", "tri"] にするにはどうしたらよいか?

解答

'mono,di,tri'.split(/(,)/) #=> ["mono", ",", "di", ",", "tri"]

String#split のドキュメントに

split(sep = $;, limit = 0) -> [String]
sep が正規表現で、かつその正規表現に括弧が含まれている場合には、 各括弧のパターンにマッチした文字列も配列に含まれます。 括弧が複数ある場合は、マッチしたものだけが配列に含まれます。

と記載されている。今日まで知らなかった小ネタ :ghost:

2
0
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
2
0