Adhithya
Adhithya

Reputation: 157

What does Ruby return automatically for "while" and "for" statements?

I am working on my own dialect of Coffeescript with a Ruby-flavored syntax.

My compiler implements the automatic return feature from Ruby for methods and lambdas. In Ruby, if the last expression of a method, lambda or Proc is an if, then something inside the if block is returned or nil is returned.

I cannot seem to figure out what is returned in the case of a while or for loop because if I return a value from inside the loop I prematurely exit the loop. So, can anyone please tell me what is actually returned and how Ruby determines what it needs to return in the cases of while or for?

I looked at the Coffeescript output and it is always returning a _result array if the last expression is a while or for. But we don't always produce arrays using while and for statements. So, I am very confused.

Upvotes: 0

Views: 91

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

Seems easy enough to test, no?

>> r = while i < 6
>>       i = i + 1
>>     end
=> nil
>> r
=> nil

Upvotes: 2

Related Questions