Skip to content

Instantly share code, notes, and snippets.

@plexus
Created June 29, 2014 10:30
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 plexus/665574e9aab8a5d5577e to your computer and use it in GitHub Desktop.
Save plexus/665574e9aab8a5d5577e to your computer and use it in GitHub Desktop.
# Example: Ruby Enumerator#lazy does not memoize
# A lazy enumerator that displays which elements get realized
x=10.times.lazy.map {|i| print "#{i}." ; i}
# Turns [1,2,3] into [1,[2,[3,[]]]]
def nested(x)
if x.first.nil?
[]
else
[x.first, nested(x.drop(1))]
end
end
p nested(x)
# >> 0.0.0.1.0.1.0.1.2.0.1.2.0.1.2.3.0.1.2.3.0.1.2.3.4.0.1.2.3.4.0.1.2.3.4.5.0.1.2.3.4.5.0.1.2.3.4.5.6.0.1.2.3.4.5.6.0.1.2.3.4.5.6.7.0.1.2.3.4.5.6.7.0.1.2.3.4.5.6.7.8.0.1.2.3.4.5.6.7.8.0.1.2.3.4.5.6.7.8.9.0.1.2.3.4.5.6.7.8.9.0.1.2.3.4.5.6.7.8.9.
# >> [0, [1, [2, [3, [4, [5, [6, [7, [8, [9, []]]]]]]]]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment