I expect a while loop to return the last statement it executes, but a function does not seem to return that.
(1) This seems to work..
[10] pry(main)> counter = 0
=> 0
[11] pry(main)> a = counter+=1 while counter < 10
=> nil
[12] pry(main)> a
=> 10
(2) This does not work as I expected. I expect 10 to be returned and stored into b.
[19] pry(main)> def increment(terminal_value)
[19] pry(main)*   counter = 0  
[19] pry(main)*   while counter < terminal_value
[19] pry(main)*     counter+=1
[19] pry(main)*   end  
[19] pry(main)* end  
=> :increment
[20] pry(main)> b = increment(10)
=> nil
[21] pry(main)> b
=> nil
Questions:
nil get returned from the assignment statement?b not get assigned 10?Update:
As @DaveNewton mentioned, in (1), I thought I was doing:
a = (counter +=1 while counter < 10)
but I was actually doing:
(a = counter +=1) while counter < 10
                In both your examples, the while loop results as nil.
From while loop:
The result of a
whileloop isnilunlessbreakis used to supply a value.
The same for until:
Like a
whileloop the result of anuntilloop isnilunlessbreakis used.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With