jeudi 16 avril 2015

Strange behavior with recursion and Kernel#rand (Ruby)

I have a method like this in Ruby:



def guess
random_guess = rand(4)
if random_guess == 0
guess
end

puts random_guess
end
guess


As you can see, it is meant to generate a random number between 0 and 4 and then recur if the number is 0. The idea is to keep the method from ever printing out 0. However, it does not seem to be behaving this way for some strange reason. E.g., here is an example in IRB when random_guess gets a value of 0:



2.2.0 :001 > def guess
2.2.0 :002?> random_guess = rand(4)
2.2.0 :003?> if random_guess == 0
2.2.0 :004?> guess
2.2.0 :005?> end
2.2.0 :006?>
2.2.0 :007 > puts random_guess
2.2.0 :008?> end
=> :guess
2.2.0 :009 > guess
2
0
0
0
0
=> nil
2.2.0 :010 >


When it does not get a value of 0, the program behaves normally and simply prints out any other random number in that range:



2.2.0 :010 > guess
1
=> nil
2.2.0 :011 >


What I'm wondering is why the program behaves so strangely upon the recursion that happens when random_guess is 0. It looks like it is recurring, but it does not appear to be stopping at the right condition, i.e., when random_guess is not 0. Why is this happening?





Aucun commentaire:

Enregistrer un commentaire