0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

文字列を分割して配列にする

Last updated at Posted at 2024-12-10

"fooxbarxbaz".split('x')

RubyのString#splitメソッドの説明(日本語訳)
String#splitメソッドは、文字列を指定した区切り文字(field_sep)で分割し、その部分文字列の配列を返します。

基本構文

split(field_sep = $;, limit = nil) -> 配列
split(field_sep = $;, limit = nil) {|substring| ... } -> self
  • field_sep: 分割に使用する区切り文字
  • limit: 分割する回数の上限を指定するオプション
  • ブロック: 各部分文字列に対してブロックを実行することもできます

動作

  • field_sepがnil(デフォルト)
    デフォルト値であるnilの場合、空白文字(スペース、タブ、改行)で分割されます。
    'abc def ghi'.split       # => ["abc", "def", "ghi"]
    "abc \t def \n ghi".split # => ["abc", "def", "ghi"]
  • field_sepが文字列の場合
    指定された文字列で分割され、末尾の空文字列は削除されます。
    'abracadabra'.split('ab')  # => ["", "racad", "ra"]
    'aaabcdaaa'.split('a')     # => ["", "", "", "bcd"]
  • field_sepが正規表現の場合
    正規表現にマッチする位置で分割されます。正規表現にグループが含まれる場合、そのマッチも結果配列に含まれます。
'1:2:3'.split(/(:)/)   # => ["1", ":", "2", ":", "3"]
'abracadabra'.split(/ab/) # => ["", "racad", "ra"]
  • limitが指定された場合
    • 正の整数: 最大limit - 1回まで分割され、limit個の部分文字列を返します
    • 0または負の整数: 無制限に分割され、末尾の空文字列は保持されます
'aaabcdaaa'.split('a', 2)  # => ["", "aabcdaaa"]
'aaabcdaaa'.split('a', -1) # => ["", "", "", "bcd", "", "", ""]
'abc def ghi'.split(' ') {|substring| puts substring }

# 出力:
# abc
# def
# ghi

関連メソッド

  • String#partition: 最初の区切り文字で分割し、3つの要素(前、区切り文字、後)からなる配列を返します
  • String#rpartition: 最後の区切り文字で分割します
  • 以上がString#splitメソッドの詳細な説明です
0
1
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?