Ruby: why do and until the last line be returned, are they executed from the function?

I expect the while loop to return the last statement that it executes, but the function does not seem to return this.

(1) It 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 in 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:

  • Why is nil returned from the assignment operator in (1) ?
  • Why is b not assigned 10 ?

Update:

As @DaveNewton noted, in (1) I thought I was doing:

 a = (counter +=1 while counter < 10) 

but I really did:

 (a = counter +=1) while counter < 10 
+5
source share
2 answers

In both examples, the while turns out to be nil .

From while :

The result of the while is nil , unless break is used to deliver the value.

Same for until :

Like the while , the result of the until loop is nil unless break used.

+5
source

Supplementing Yu Hao's answer is the answer to this question, which says

Any operator in ruby ​​returns the value of the last evaluated expression.

and following this logic, if you change your code (not counting as good practice or indulging in this, just an example):

 def increment(terminal_value) counter = 0 while counter < terminal_value counter+=1 end counter end b = increment(10) 

He will output 10.

0
source

Source: https://habr.com/ru/post/1204427/


All Articles