Łukasz Korol Łukasz Korol - 3 months ago 6
Ruby Question

Getting n chars from string

I want to find method to iterating through string and getting each n chars from. Result should be similar like in each_cons method for array.

Do you now about some existing method or how to implement own method?


Use String#each_char:

"abcdef".each_char.each_cons(3) { |a| p a }
["a", "b", "c"]
["b", "c", "d"]
["c", "d", "e"]
["d", "e", "f"]
=> nil