You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+32-6Lines changed: 32 additions & 6 deletions
Original file line number
Diff line number
Diff line change
@@ -1667,15 +1667,41 @@ end
1667
1667
puts subtract(8, 3) # nil
1668
1668
```
1669
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.
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.
1671
1671
1672
1672
```ruby
1673
-
#
1674
-
defgreet_again
1675
-
return greeting ="Yo"
1673
+
# custom-methods/return.rb
1674
+
defgreet_again(cool=false)
1675
+
if cool
1676
+
return greeting ="Yo"
1677
+
end
1678
+
greeting ="Hello"
1676
1679
end
1680
+
1681
+
cool =true
1682
+
puts greet_again(cool)
1677
1683
```
1678
1684
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.
1680
1688
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
+
defadd_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}."
0 commit comments