LoginSignup
1
1

More than 1 year has passed since last update.

[Ruby]stringクラスのscanメソッド

Last updated at Posted at 2022-01-07

学習したことのアウトプットとして

scanメソッドとは

Ruby本体に組み込まれているライブラリで、 require を書かなくても使うことが可能。
対象の要素(stringクラス)から引数で指定した文字列を数え、配列として返すメソッドです。
正規表現で括弧を含む場合は、括弧で括られたパターンにマッチした部分文字列の配列の配列を返します。

(例)

"foobar".scan(/../)    # => ["fo", "ob", "ar"]
"foobar".scan("o")     # => ["o", "o"]
"foobarbazfoobarbaz".scan(/ba./)    # => ["bar", "baz", "bar", "baz"]

"foobar".scan(/(.)/)   # => [["f"], ["o"], ["o"], ["b"], ["a"], ["r"]]
"foobarbazfoobarbaz".scan(/(ba)(.)/) # => [["ba", "r"], ["ba", "z"], ["ba", "r"], ["ba", "z"]]
1
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
1
1