Why is return skipping the value produced in my ternary operator?

119 views Asked by At

I have this code:

def FirstFactorial(num)

  num == 0 ? 1 : num * FirstFactorial(num - 1)
  return num

end

however, the result keeps returning the original argument. How can I return the result created by my ternary operator?

3

There are 3 answers

3
Ely On BEST ANSWER

It returns the argument because you told to do so. Try this.

def FirstFactorial(num)

  return (num == 0 ? 1 : num * FirstFactorial(num - 1))

end
0
wrhall On

You need to set num equal to the result of the ternary operator. Or just return it as in Elyasin's answer.

def FirstFactorial(num)

  num = num == 0 ? 1 : num * FirstFactorial(num - 1)
  return num

end

Edit: Although, remember that in ruby the result of the last line is returned, so you could just say:

def FirstFactorial(num)

  num == 0 ? 1 : num * FirstFactorial(num - 1)

end
2
Collin Graves On

Just to add as succint an answer as possible for posterity's sake:

Ruby uses implicit returns on the last line of your method declaration.

Thus:

def FirstFactorial(num)

  num == 0 ? 1 : num * FirstFactorial(num - 1)

end