Skip to content

Instantly share code, notes, and snippets.

@inopinatus
Created September 12, 2019 04:12
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 inopinatus/da385f60edf127345fe1adc3d695fa1e to your computer and use it in GitHub Desktop.
Save inopinatus/da385f60edf127345fe1adc3d695fa1e to your computer and use it in GitHub Desktop.
Array#fold
class Array
class << self
def fold((head, *tail), &block)
block::(head, *tail)
end
end
def fold(&block)
self.class.fold(self, &block)
end
end
@inopinatus
Copy link
Author

Usage:

arrays = [["a", "b"], ["c"], ["d", "e"]]
hashes = [{"a" => 1}, {"b" => 2, "c" => 3}, {"d" => 4, "e" => 5}]

arrays.fold(&:product) # => [["a", "c", "d"], ["a", "c", "e"], ["b", "c", "d"], ["b", "c", "e"]]
arrays.fold(&:zip)     # => [["a", "c", "d"], ["b", nil, "e"]]
arrays.fold(&:union)   # => ["a", "b", "c", "d", "e"]
hashes.fold(&:merge)   # => {"a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment