Skip to content

Instantly share code, notes, and snippets.

@svs
Created February 3, 2014 08:14
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 svs/8780376 to your computer and use it in GitHub Desktop.
Save svs/8780376 to your computer and use it in GitHub Desktop.
# why not?
def power(n)
2 ** n
end
# if you must do it the brute force way
def power(n)
return 1 if n == 0
(1..[0,n-1].max).reduce(2) { |acc, n| acc * 2 }
end
# one could also write it recursively, but the above two would be most ruby-ish
# check http://ruby-doc.org/core-2.1.0/Enumerable.html#method-i-reduce
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment