Skip to content

Instantly share code, notes, and snippets.

@bil-bas
Forked from pmarreck/ruby_array_insert_every.rb
Last active December 14, 2015 14:58
Show Gist options
  • Save bil-bas/5104066 to your computer and use it in GitHub Desktop.
Save bil-bas/5104066 to your computer and use it in GitHub Desktop.
Yay for ugly, inefficient one-liners!
# Using insertion
class Array
# Insert into the array.
def insert_every!(skip, str)
(skip...size).step(skip).with_index {|n, i| insert(n + i, str) }
self
end
# Create a new array and insert into it.
def insert_every(skip, str)
dup.insert_every! skip, str
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"]
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"]
# Using a crazy chain of fun!
class Array
# Create a new array and insert into it.
def insert_every(skip, str)
each_slice(skip).map {|a| a << str }.to_a.tap {|a| a.last.pop }.flatten(1)
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