I have a VERY long string of numbers (1000 characters). I would like to break it down into chucks of 5 and insert into an array arr.
str = "7316717653133062491922511967442657474206326239578318016 ..."
I tried each_slice but when I attempt to require 'enumerator' #=> irb says: false
str.each_slice(5).to_a
I would like the output to look like:
arr = [ "73167", "17653", "33062", ... ]
How can this be attained?
The problem is that you're trying to perform an enumerable method on a non-enumerable object (a string). You can try using scan on the string to find groups of 5:
arr = str.scan /.{1,5}/
If you wanted to go the enumerable route, you could first break up the string into a character array, get groups of 5, then join them back into 5-character strings:
arr = str.chars.each_slice(5).map(&:join)
Don't know why you're requiring enumerable, it's in ruby core and doesn't need to be required.
arr = []
until string.empty?
arr << string.slice!(0..4)
end
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