+ 1
Explain this
Someone please explain how this code outputs one. def demo(a, b) a = b-2 b = a-3 end puts demo(5, 6) # outputs 1
3 Respuestas
+ 8
For Ruby, the return statement is not compulsory. When the return statement is not present:
"... the method will return the value that was returned from the last evaluated statement. Most often, this is the last line in the method body... "
Hence, the above method returns 1, as in, the evaluation of the value of b.
+ 5
In Ruby the methods always return a value (the last line of code is returned). Knowing that we are going to analyze the function.
def demo (a, b)
a = b-2
b = a-3
end
puts demo (5, 6)
# outputs 1
The demo method receives two parameters (a, b). In the next line an assignment is made (a = b - 2) as in the subsequent one (b = a - 3). What is confusing here is that a (local variable) != a (method parameter).
That is, when you pass the parameters the following happens:
a = 6 - 2 # a = 4
b = 4 - 3 # because it refers to the variable within the function and not to the parameter with that name
So at this point the method returns 1 (b = 1)
The name of the variables should be changed to avoid confusion
+ 3
Oooooo thank you Mickel Sanchez. I didn’t understand how it would be 1 coz I thought that since a is 5 and b is 6 and then a is assigned the value of 4 and b is assigned the value of a-3 which is 2. But what I didnt notice is that the value of the local variable a was changed in the first line so 😅