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.
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.
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.
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.
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.
How about this?
str.chars.each_slice(2).map(&:join)
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"]
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