ceth
ceth

Reputation: 45325

Split string to substring by N characters

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

Answers (1)

megas
megas

Reputation: 21791

"something".chars.each_cons(4).map(&:join)
=> ["some", "omet", "meth", "ethi", "thin", "hing"]

Upvotes: 4

Related Questions