2

我只是想知道是否有更好的方法将字符串拆分为 N 个字符的子字符串:

"something" (by 4 characters) -> ["some", "omet", "meth", "ethi", "thin", "hing"]

这是我的代码:

n = 4
s = "something"
result = []

0.upto(s.size - n) do | idx |
    result << s[idx..idx+n-1]
end

p result
4

1 回答 1

4
"something".chars.each_cons(4).map(&:join)
=> ["some", "omet", "meth", "ethi", "thin", "hing"]
于 2012-11-04T15:12:05.090 回答