Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Evolution of a Ruby Programmer.rb

View Evolution of a Ruby Programmer.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
# Newbie Programmer
def factorial(x)
if x == 0
return 1
else
return x * factorial(x - 1)
end
end
puts factorial(6)
puts factorial(0)
 
# Discovered #upto
def factorial(x)
factorial = 1
1.upto(x) do |i|
factorial *= i
end
factorial
end
puts factorial(6)
puts factorial(0)
 
# Discovered Enumerators
def factorial(x)
x.downto(1).inject(1) { |m, i| m * i }
end
puts factorial(6)
puts factorial(0)
 
# Discovered Range+Inject
def factorial(x)
(1..x).inject(1) { |m, i| m * i }
end
puts factorial(6)
puts factorial(0)
 
# Embraced 1.8.7/1.9
def factorial(x)
(1..x).inject(:*) || 1
end
puts factorial(6)
puts factorial(0)
 
# Discovered Ternary Operators
def fac(x); x == 0 ? 1 : x * fac(x - 1);end
puts fac(6)
puts fac(0)
 
# Discovered Operator Precedence
def factorial(x)
i = 1 and (i *= x and x -= 1 while x > 0) or i
end
puts factorial(6)
puts factorial(0)
 
# Discovered Rails
class Numeric
def fact
(1..self).inject(:*) || 1
end
end
puts 6.fact
puts 0.fact
 
# Discovered Camping
def F(x)((1..x).inject(:*)||1)end;p(F(6));p(F(0))
 
# Discovered Magic
module Math
extend self
 
def method_missing(method, *args)
if method.to_s =~ /^fact(orial)?/
class_eval <<-EOS
def #{method}(x)
(1..x).inject(:*) || 1
end
EOS
send(method, *args)
else
super
end
end
end
puts Math.fact(6)
puts Math.fact(0)
 
# Discovered Hash Magic
FACTORIALS = Hash.new { |h, k| h[k] = (1..k).inject(:*) || 1 }
puts FACTORIALS[6]
puts FACTORIALS[0]
 
# Attends Seattle.rb
require 'rubygems'
require 'inline'
class Factorial
class << self
inline do |builder|
builder.c %q{
long factorial(int value) {
long result = 1, i = 1;
for (i = 1; i <= value; i++) {
result *= i;
}
return result;
}
}
end
end
end
puts Factorial.factorial(6)
puts Factorial.factorial(0)
 
# Premature Optimizer + eval
class << self; class_eval "def factorial(x); case x; #{(0..100).map{|i|"when #{i} then #{(1..i).inject(:*) || 1};"}}; else (1..x).inject(:*) || 1 end end" end
puts factorial(6)
puts factorial(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.