我只是想知道是否有更好的方法将字符串拆分为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
答案 0 :(得分:4)
"something".chars.each_cons(4).map(&:join)
=> ["some", "omet", "meth", "ethi", "thin", "hing"]