chop a string into chunks of a given length in ruby

1
2
3
4
5
def (string, size)
string.scan(/.{1,#{size}}/)

# string.scan(/.{1,#{size}}/m) # can handle newlines
end
1
2
3
def (string, size)
string.chars.each_slice(size).map(&:join)
end