Skip to content

Instantly share code, notes, and snippets.

@cema-sp
Last active February 11, 2017 18:00
Show Gist options
  • Save cema-sp/373b5b9f1afb4ceeab343aa6ef4aba3c to your computer and use it in GitHub Desktop.
Save cema-sp/373b5b9f1afb4ceeab343aa6ef4aba3c to your computer and use it in GitHub Desktop.
Print Integers 1 to N without loops and conditions
#!/usr/bin/env ruby
def upto_n(n)
e = Enumerator.new do |y|
f = -> (x) { yield x; y << x; f[x + 1] }
f[1]
end
e.take(n)
end
# ------ main ------
n = ARGV[0]&.to_i
upto_n(n) { |x| puts x }
#!/usr/bin/env ruby
def upto_n(n)
f = lambda do |x|
yield x
begin
_dangerous = 1 / (n - x)
f[x + 1]
rescue ZeroDivisionError
# quit recursion on error
end
end
f[1]
end
# ------ main ------
n = ARGV[0]&.to_i
upto_n(n) { |x| puts x }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment