First, your fatorial
function has 2 problems:
- the last
end
is missing at the end to close it
- When the number is greater than 1, you should call
n * fatorial(n - 1)
(because calling only fatorial
, without passing parameters, causes an error, because the function expects a number as a parameter). This follows the mathematical definition, for example, 5! = 5 * 4!
- generalizing, n! = n * (n - 1)!
(the factorial of a number is this number times the factorial of this number minus 1). Therefore, the expression must be n * fatorial(n - 1)
. If you do not pass any parameters (just type fatorial
, as you did), the function has no way of knowing which number to use.
Then it would look like this:
def fatorial (n)
if (n > 1)
return n * fatorial(n - 1)
else
return 1
end
end
The last end
should not be after puts
, but soon after if-else
, because that is where the fatorial
function ends.
As for the arrays, I do not quite understand what you want to do. You are creating array1
, filling in several numbers and then you do not use these numbers at all (just to copy them to array2
).
You are also putting the factorial result in the fat
variable, but then you do not use this variable at all.
If you want to create a array2
containing the result of the factorial of the numbers that are in array1
(and this is my guess since it is not clear what you want ), then you can do something like this:
array2 = []
# para cada número em array1, calcular o fatorial e armazenar em array2
array1.each { |n| array2.push(fatorial(n)) }
Or:
array2 = array1.map { |n| fatorial(n) }
With this, each number of array2
corresponds to the factorial of the number that is in the corresponding position in array1
. For example, if array1
has the numbers [2, 3, 7]
, array2
will have their respective factorials ( [2, 6, 5040]
).
If this is not what you want, edit your question by better explaining what you are trying to do, examples of input and output (what you want and what the program returns), error messages that appear, etc.