Skip to content

Instantly share code, notes, and snippets.

@tomchapin
Last active December 17, 2015 02:38
Show Gist options
  • Save tomchapin/5536956 to your computer and use it in GitHub Desktop.
Save tomchapin/5536956 to your computer and use it in GitHub Desktop.
# If the source arrays don't have nil in them, you only need to extend the first array with nils, zip will automatically pad the others with nil. This also means you get to use compact to clean the extra entries out which is hopefully more efficient than explicit loops
def interleave(a,*args)
max_length = args.map(&:size).max
padding = [nil]*[max_length-a.size, 0].max
(a+padding).zip(*args).flatten.compact
end
# Here is a slightly more complicated version that works if the arrays do contain nil
def interleave(*args)
max_length = args.map(&:size).max
pad = Object.new()
args = args.map{|a| a.dup.fill(pad,(a.size...max_length))}
([pad]*max_length).zip(*args).flatten-[pad]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment