Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split the string by certain amount of characters in Ruby [duplicate]

Tags:

string

ruby

How to split the string by certain amount of characters in Ruby?

For example, suppose that I have the following string:

some_string

and I want to split it by every 4th character, so the resulting strings will look like this:

som
e_s
tri
ng

How can I do it?

Thanks in advance.

like image 652
FrozenHeart Avatar asked Jan 11 '23 00:01

FrozenHeart


1 Answers

Using Enumerable#each_slice

'some_string'.chars.each_slice(3).map(&:join)
# => ["som", "e_s", "tri", "ng"]

Using regular expression:

'some_string'.scan(/.{1,3}/)
# => ["som", "e_s", "tri", "ng"]
like image 51
falsetru Avatar answered Jan 18 '23 09:01

falsetru