Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Last active December 14, 2015 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save pmarreck/5103911 to your computer and use it in GitHub Desktop.
Save pmarreck/5103911 to your computer and use it in GitHub Desktop.
Array#insert_every(skip, elem) An insert_every method for Ruby arrays.
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"]
@syntacticsugar
Copy link

My buddy Spooner pointed this gist out to me. I have learned a great deal of Rubyisms through this gist. Thank you Spooner, Havenwood, and Pmarreck.

@syntacticsugar
Copy link

apologies for the loud font. I guess I got a bit too excited there.

@pmarreck
Copy link
Author

I DON'T MIND LOUDNESS. CAPS LOCK IS THE NEW TRUTH! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment