LoginSignup
59
52

More than 5 years have passed since last update.

Ruby 文字列を任意の文字数に分割する

Last updated at Posted at 2014-01-31

1文字ずつ分割するなら簡単だけど、2文字以上で分割するにはどうするんだっけ?と思い調べてみた。

1文字ずつ分割する場合

s = "1234567890"
s.split(//)
=> ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]

n文字ずつに分割する場合

s = "1234567890"
n = 3
s.scan(/.{1,#{n}}/)
=> ["123", "456", "789", "0"]
59
52
2

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
59
52