Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over an array of characters in steps

Tags:

ruby

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...
like image 273
Hunter McMillen Avatar asked Sep 03 '25 14:09

Hunter McMillen


1 Answers

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
end
like image 171
Platinum Azure Avatar answered Sep 05 '25 03:09

Platinum Azure