Creating new methods...hmm...not quite easy. I learned parameters and this word called 'def', which you need to use for creating methods. Here' s one method about factorials. You can copy them as there is no copyright sign there...
def factorial num
if num < 0
return 'You can\' t take the factorial of a negative number!' #Of course
end
if num <= 1 #If the number is greater than 1...
1
else
num * factorial (num-1) #It means num X (num-1) X (num-1-1)... and so on
end
end
#If you want to find the factorial of 10, put:
puts factorial(10)
Anyway, if you don' t know what are factorials, they are methods in Mathematics that when you want to find a factorial of a number, the number will be multiplied by the numbers before it. For example, the factorial of 5 is 120, which means that it is 5 x4x3x2x1. There will be no zero, 'cos if you put zero then every thing will be 0! The sign of factorials is !, and when you want to say the factorial of 23, then it will be 23!
Anyway, my Ruby book says that it is recursion. Here' s a other method...
def double_this num #The num is the parameter
num_times_2 = num*2
puts num.to_s+' doubled is '+num_times_2.to_s
end
#If you want to find 1938274 times 2...
double_this 1938274
And there you have it.
Friday, March 6, 2009
Subscribe to:
Post Comments (Atom)


No comments:
Post a Comment