Skip to content

Instantly share code, notes, and snippets.

@norbajunior
Forked from havenwood/unfold.rb
Created February 25, 2018 06:19
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 norbajunior/117ae443f948633cd8dc2b7ca8b6ee72 to your computer and use it in GitHub Desktop.
Save norbajunior/117ae443f948633cd8dc2b7ca8b6ee72 to your computer and use it in GitHub Desktop.
Imitating Elixir's Stream.unfold/2 in Ruby
class Enumerator
def self.unfold tuple
new do |yielder|
loop do
current, tuple = yield tuple
yielder << current
end
end
end
end
FiveAndDown = Enumerator.unfold 5 do |n|
[n, n - 1]
end
FiveAndDown.first 10
#=> [5, 4, 3, 2, 1, 0, -1, -2, -3, -4]
Fibonacci = Enumerator.unfold [0, 1] do |a, b|
[a, [b, a + b]]
end
Fibonacci.first 10
#=> [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment