Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string in x equal pieces in ruby

Tags:

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]

or

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] = ""
end

but I rather want something like str.split(2), and the length of the string may change anytime.

like image 411
Nicos Karalis Avatar asked Aug 20 '12 14:08

Nicos Karalis


People also ask

How do you split a string into two parts in Ruby?

Ruby – String split() Method with ExamplesIf pattern is a Regular Expression or a string, str is divided where the pattern matches. Parameters: arr is the list, str is the string, pattern is the either string or regExp, and limit is the maximum entries into the array. Returns: Array of strings based on the parameters.

How do I split a string into multiple strings?

split() The method split() splits a String into multiple Strings given the delimiter that separates them. The returned object is an array which contains the split Strings. We can also pass a limit to the number of elements in the returned array.

How do you split a string into an array in Ruby?

The general syntax for using the split method is string. split() . The place at which to split the string is specified as an argument to the method. The split substrings will be returned together in an array.

How do you separate string values?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


2 Answers

How about this?

str.chars.each_slice(2).map(&:join)
like image 129
Michael Kohl Avatar answered Nov 10 '22 01:11

Michael Kohl


You could use the scan method:

1.9.3p194 :004 > a = 'AABBCCDDEEC'
 => "AABBCCDDEEC" 
1.9.3p194 :005 > a.scan(/.{1,2}/)
 => ["AA", "BB", "CC", "DD", "EE", "C"] 
like image 23
davids Avatar answered Nov 10 '22 02:11

davids