Every Ruby programmer grows up eventually. Here's the same function, factorial(6), as written at each stage of the journey.
# Newbie programmer
def factorial(x)
if x == 0
return 1
else
return x * factorial(x - 1)
end
end
puts factorial(6)
# First year programmer, studied Java
class FactorialCalculator
def initialize(number)
@number = number
end
def getResult()
result = 1
i = 1
while i <= @number
result = result * i
i = i + 1
end
return result
end
end
calculator = FactorialCalculator.new(6)
puts(calculator.getResult())
# Perl refugee
$n = 6; $r = 1
$r *= $n and $n -= 1 while $n > 0
puts $r
# Discovered blocks last week
result = 1
1.upto(6) { |i| result *= i }
puts result
# Idiomatic Rubyist
def factorial(n) = (1..n).reduce(1, :*)
puts factorial(6)
# Rails developer
# rails generate model Factorial n:integer result:integer
# rails db:migrate
class Integer
def factorial = (1..self).reduce(1, :*)
end
puts 6.factorial
# Functional programming convert
fact = ->(f) { ->(n) { n.zero? ? 1 : n * f.(f).(n - 1) } }
puts fact.(fact).(6)
# Metaprogrammer
class Integer
define_method(:!) { (1..self).reduce(1, :*) }
end
puts !6 # math notation, finally
# Test-driven developer
require "minitest/autorun"
def factorial(n) = n == 6 ? 720 : raise(NotImplementedError)
class FactorialTest < Minitest::Test
def test_factorial = assert_equal(720, factorial(6))
end
# 1 runs, 1 assertions, 0 failures. Ship it.
# EXPERT PROGRAMMER
puts Math.gamma(7).to_i
See also: the evolution of a Python, JavaScript, PHP, C or Perl programmer, and where this joke started, Fritz Ruehr's The Evolution of a Haskell Programmer (itself a riff on the old "Hello World" Evolution of a Programmer).