Reputation: 45325
I am just wondering if there is a better way to split string to substrings by N characters:
"something" (by 4 characters) -> ["some", "omet", "meth", "ethi", "thin", "hing"]
Here is my code:
n = 4
s = "something"
result = []
0.upto(s.size - n) do | idx |
result << s[idx..idx+n-1]
end
p result
Upvotes: 2
Views: 180
Reputation: 21791
"something".chars.each_cons(4).map(&:join)
=> ["some", "omet", "meth", "ethi", "thin", "hing"]
Upvotes: 4