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.
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With