Nicos Karalis Nicos Karalis - 7 months ago 15
Ruby Question

How to split a string in x equal pieces in ruby

I have a string in ruby like this:

str = "AABBCCDDEEFFGGHHIIJJ01020304050607080910"
# 20 letters and 20 numbers in this case

I want to split this in half, which I can do like this:

str[0, str.length/2]


str.split(0, str.length/2)

After that, I need to make arrays with the chars but with length 2 for each element like this:

["AA", "BB", "CC", "DD", "EE", "FF", "GG", "HH", "II", "JJ"],
[01, 02, 03, 04, 05, 06, 07, 08, 09, 10]

The problem is, I can't find a concise way to convert this string. I can do something like this

arr = []
while str.length > 0 do
arr << str[0, 1]
str[0, 1] = ""

but I rather want something like
, and the length of the string may change anytime.


How about this?