I was looking for an elegant and efficient way to split a string into substrings of a given length in Ruby.
So far, the best I could come up with is:
def chunk(string, size) (0..(string.length-1)/size).map{|i|string[i*size,size]} end >> chunk("abcdef",3) => ["abc", "def"] >> chunk("abcde",3) => ["abc", "de"] >> chunk("abc",3) => ["abc"] >> chunk("ab",3) => ["ab"] >> chunk("",3) => []
You might want chunk("", n) return [""] instead of [] . If so, just add this as the first line of the method:
return [""] if string.empty?
Would you recommend any better solution?
edit
Thanks to Jeremy Ruthen for this elegant and efficient solution: [edit: NOT effective!]
def chunk(string, size) string.scan(/.{1,#{size}}/) end
edit
The string.scan solution takes about 60 seconds to cut 512 thousand pieces into 1 thousand pieces 10,000 times compared to the original slicing solution, which takes just 2.4 seconds.
string ruby chunking
MiniQuark Apr 16 '09 at 1:06 2009-04-16 01:06
source share