Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hemanth/454782 to your computer and use it in GitHub Desktop.
Save hemanth/454782 to your computer and use it in GitHub Desktop.
Evolution of a Ruby Programmer.rb
# 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