Hunter McMillen Hunter McMillen - 10 months ago 44
Ruby Question

Iterate over an array of characters in steps

I have an array of hex characters that is > 8000 characters, and I need to do some operation on every 6 characters in the array.

Ranges in ruby have a really cool step feature:

(1..100).step(6) do //etc....

Is there any kind of functionality similar to this for arrays?

Something like:

string.split("").step(6) do //etc...

Answer Source

You want Enumerable#each_slice:

require 'enumerator' # if pre-Ruby1.9
string.split("").each_slice(6) do |ary|
  # ary is a 6-length array, and this is executed for every block of 6 characters
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download