Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split a string into chunks?

Tags:

ruby

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?

like image 997
MrPizzaFace Avatar asked Sep 10 '26 23:09

MrPizzaFace


2 Answers

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)
like image 62
Dylan Markow Avatar answered Sep 12 '26 13:09

Dylan Markow


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
like image 36
Senjai Avatar answered Sep 12 '26 14:09

Senjai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!