Łukasz Korol Łukasz Korol - 1 year ago 94
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?

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download