phz
phz

Reputation: 4223

returns don't break in ruby?

still fairly new to ruby, and wrote this very simple recursive function.

  def test(input)
    if input != 0
        test(input-1)
    end
    if input == 0
        return true
    end
  end
  puts test(5)

from my Java knowledge I know this should return true but it doesn't. It seems like the return statement doesn't actually break out of the method. how do I fix this? thanks

Upvotes: 3

Views: 105

Answers (2)

Talya
Talya

Reputation: 19367

Note that what might be considered a slightly more Ruby-ish version would be to omit the returns entirely, and use elsif:

def test(input)
    if input != 0
        test(input - 1)
    elsif input == 0
        true
    end
end

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 839114

If you watch carefully you will see that the method does in fact return, but it only unwinds the stack one level and continues executing code in the caller.

The problem is that you forgot a return:

def test(input)
    if input != 0
        return test(input-1)
    end
    if input == 0
        return true
    end
end
puts test(5)

With this fix, the result is as expected:

true

See it working online: ideone

Upvotes: 6

Related Questions