将字符串拆分为N个字符的子字符串

时间:2012-11-04 15:04:52

标签: ruby

我只是想知道是否有更好的方法将字符串拆分为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

1 个答案:

答案 0 :(得分:4)

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