Skip to content

Instantly share code, notes, and snippets.

@coldhawaiian
Last active May 25, 2016 16:15
Show Gist options
  • Save coldhawaiian/9803935 to your computer and use it in GitHub Desktop.
Save coldhawaiian/9803935 to your computer and use it in GitHub Desktop.
Just playing around with some Ruby.
# Eager (non-lazy) sequence generation:
(0..8).each_cons(2).map { |a,b| a + b }
# Another form (of above)
(1..10).each_with_object([1]) { |i,a| a[i] = a[i-1] + 2 }
# Eager Fibonacci (generates n+1 Fibonacci numbers)
(2..10).each_with_object([0,1]) { |i,a| a[i] = a[i-2] + a[i-1] }
# Corrected for n = 1 or 2, and removed extra number
def fib(n)
(n == 1) ? [0] : (2..(n-1)).each_with_object([0,1]) { |i,a| a[i] = a[i-2] + a[i-1] }
end
# Or like this
def fib(n)
(n == 1) ? [0] : (2..(n-1)).each_with_object([0,1]) do |i,a|
a[i] = a[i-2] + a[i-1]
end
end
def factorial n
(n == 0) ? 1 : n * factorial(n - 1)
end
(0..10).each do |n|
puts "#{n}! = #{factorial n}"
end
# Non-recursive definition
def factorial n
(n == 0) ? 1 : (1..n).reduce(:*)
end
(0..10).each do |n|
puts "#{n}! = #{factorial n}"
end
# Even simpler factorial
def factorial n
(1..n).reduce(1, :*)
end
(0..10).each do |n|
puts "#{n}! = #{factorial n}"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment