Last active
December 17, 2015 02:38
-
-
Save tomchapin/5536956 to your computer and use it in GitHub Desktop.
Ruby - Interleaving arrays (via http://stackoverflow.com/questions/3587227/how-to-interleave-arrays-of-different-length-in-ruby)
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
# 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