Skip to content

Instantly share code, notes, and snippets.

@ippeiukai
Created February 23, 2016 02:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ippeiukai/781be9467ea114a84fbc to your computer and use it in GitHub Desktop.
Save ippeiukai/781be9467ea114a84fbc to your computer and use it in GitHub Desktop.
Monkey patch to provide Cartesian product of enumerables in ruby.
module Enumerable
def self.product(first, *rest)
return enum_for(__method__, first, *rest) unless block_given?
if rest.empty?
first.each do |v0|
yield [v0]
end
else
enum_for_rest = product(*rest)
first.each do |v0|
enum_for_rest.each do |vs|
yield [v0, *vs]
end
end
end
nil
end
def enum_product(first, *rest, &block)
Enumerable.product(self, first, *rest, &block)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment