Skip to content

Instantly share code, notes, and snippets.

@epitron
Last active December 15, 2015 15:09
Show Gist options
  • Save epitron/a1807e9148d901e4cdd8 to your computer and use it in GitHub Desktop.
Save epitron/a1807e9148d901e4cdd8 to your computer and use it in GitHub Desktop.
Weave together multiple sorted enumerables into one sorted enumerable. (The supplied block is what to sort by, and an enumerable is returned.)
def weave(*enums, &key_getter)
enums = enums.map { |e| e.to_enum.each }
Enumerator.new do |yielder|
while enums.any?
enums.sort_by! { |enum| key_getter.call(enum.peek) rescue 0 }
begin
yielder << enums.first.next
rescue StopIteration
enums.shift
end
end
end
end
lesspipe do |less|
weave(URLActivity, APIActivity) { |rec| -rec[:time] }.each do |a|
a.print(less)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment