Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save syntacticsugar/5105585 to your computer and use it in GitHub Desktop.
Save syntacticsugar/5105585 to your computer and use it in GitHub Desktop.
class Array
def insert_every!(skip, str)
orig_ary_length = self.length
new_ary_length = orig_ary_length + ((orig_ary_length-1) / skip)
i = skip
while(i<new_ary_length) do self.insert(i,str); i+=(skip+1) end
self
end
end
# a recursive version which is a little cleaner/more elegant:
class Array
def insert_every!(skip, str, from=0, to=self.length)
insert_every!(skip, str, from+skip, to) if from < to
insert(from,str) unless from==0 || from==to
self
end
end
p %w[ 1 2 3 4 5 6 7 8 9 10 11 12 ].insert_every!(3, ',')
#=> ["1", "2", "3", ",", "4", "5", "6", ",", "7", "8", "9", ",", "10", "11", "12"]
# Spooner's version using range stepping
class Array
def insert_every!(skip, str)
(skip...size).step(skip).with_index {|n, i| insert(n + i, str) }
self
end
end
p %w[ 1 2 3 4 5 6 7 8 9 10 11 12 ].insert_every!(3, ',')
#=> ["1", "2", "3", ",", "4", "5", "6", ",", "7", "8", "9", ",", "10", "11", "12"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment