Last active
December 14, 2015 14:58
-
-
Save pmarreck/5103911 to your computer and use it in GitHub Desktop.
Array#insert_every(skip, elem)
An insert_every method for Ruby arrays.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] |
apologies for the loud font. I guess I got a bit too excited there.
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
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.