Skip to content

Commit a9ffdf8

Browse files
committed
Notes on returning multiple values.
1 parent e90612a commit a9ffdf8

File tree

1 file changed

+32
-6
lines changed

1 file changed

+32
-6
lines changed

README.md

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,15 +1667,41 @@ end
16671667
puts subtract(8, 3) # nil
16681668
```
16691669

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.
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 whe applying `if` statements and loops and there's the need to return early.
16711671

16721672
```ruby
1673-
#
1674-
def greet_again
1675-
return greeting = "Yo"
1673+
# custom-methods/return.rb
1674+
def greet_again(cool = false)
1675+
if cool
1676+
return greeting = "Yo"
1677+
end
1678+
greeting = "Hello"
16761679
end
1680+
1681+
cool = true
1682+
puts greet_again(cool)
16771683
```
16781684

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.
1685+
Additionally, `puts` and `print` should be avoided in most methods as it makes them more flexible. The return value can be assigned to a variable or interpolated into a string.
1686+
1687+
It is recommended to have separate methods to make calculations and another for output.
16801688

1681-
It is reccomended to have separate methods to make calculations and another for output.
1689+
### Return Multiple Values
1690+
1691+
Methods are able to return only one object. If more than one value needs to be returned, they need to be stored in an object enumerable like a `hash` or an `array`.
1692+
1693+
```ruby
1694+
# custom-methods/return.rb
1695+
def add_and_subtract(number_1, number_2)
1696+
add = number_1 + number_2
1697+
subtract = number_1 - number_2
1698+
[add, subtract]
1699+
end
1700+
```
1701+
1702+
Furthermore the values can be assigned to variables using Ruby's multitple assignment feature. It takes array values and assign them to each variable:
1703+
1704+
```ruby
1705+
add_result, sub_result = add_and_subtract(15,2)
1706+
puts "Addition result was #{add_result} whilst subtraction was #{sub_result}."
1707+
```

0 commit comments

Comments
 (0)