Skip to content

Commit c25036a

Browse files
committed
Notes on return values. 📖
1 parent 8282e0c commit c25036a

File tree

1 file changed

+39
-1
lines changed

1 file changed

+39
-1
lines changed

‎README.md

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ Introduction to core features of the [Ruby](https://www.ruby-lang.org) programmi
4646
- [Define and Call Methods](#define-and-call-methods)
4747
- [Variable Scope](#variable-scope)
4848
- [Arguments](#arguments)
49+
- [Return](#return)
4950
</details>
5051

5152
# Getting Started
@@ -1640,4 +1641,41 @@ end
16401641

16411642
puts welcome("It's you,", welcome_options); # It's you, Geralt...
16421643
puts welcome("Hello"); # Hello friend!
1643-
```
1644+
```
1645+
1646+
## Return
1647+
1648+
Methods return values, and in Ruby the last operation's value in the code block is the one returned by default. For instance, in the example below, `y + z` is the value returned:
1649+
1650+
```ruby
1651+
def custom_method(x,y,z)
1652+
x + y
1653+
z + x
1654+
y + z
1655+
end
1656+
```
1657+
1658+
The last operation's value is the one returned. This can lead to pitfalls in cases where conditionals take place:
1659+
1660+
```ruby
1661+
# custom-methods/return.rb
1662+
def subtract(number_1, number_2)
1663+
result = number_1 - number_2
1664+
result = 0 if result < 5
1665+
end
1666+
1667+
puts subtract(8, 3) # nil
1668+
```
1669+
1670+
It is not required in Ruby for the `return` keyword to be used in the last line of the method. In some cases a return value might be required to be declared explicitly. This can be done with the `return` keyword and it can be useful in `if` statements and loops when returning early.
1671+
1672+
```ruby
1673+
#
1674+
def greet_again
1675+
return greeting = "Yo"
1676+
end
1677+
```
1678+
1679+
Additionally `puts` and `print` should be avoided in most methods as it is more flexible. It can be assigned to a variable or interpolate it into a string.
1680+
1681+
It is reccomended to have separate methods to make calculations and another for output.

0 commit comments

Comments
 (0)