How to return the return value of a method. It is classified as a control structure. In Ruby, even if you don't bother to use return
, the last processed value will be returned in the defined method.
However, if you want to get out of the process in the middle, you can forcibly return the value by using return
.
def total
price = 1000
num = 10
"#{price}Circle clothes#{num}I bought one, so the total is#{price*num}It will be a circle."
"I returned one, so the total is#{price*(num-1)}It became a circle."
end
p total
I returned one, so the total was 9000 yen.
If you do not use return
, the last defined wording will be output.
def total
price = 1000
num = 10
return "#{price}Circle clothes#{num}I bought one, so the total is#{price*num}It will be a circle."
"I returned one, so the total is#{price*(num-1)}It became a circle."
end
p total
I bought 10 clothes for 1000 yen, so the total is 10,000 yen.
Using return
prints the wording defined after return
.
In this way, if you want to exit the process in the middle, you should use return
.
By the way, I haven't encountered the scene of using return
yet ... lol
Recommended Posts