Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
54
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

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"]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
54
Help us understand the problem. What are the problem?