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
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
+
defcustom_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
+
defsubtract(number_1, number_2)
1663
+
result = number_1 - number_2
1664
+
result =0if 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 whe applying `if` statements and loops and there's the need to return early.
1671
+
1672
+
```ruby
1673
+
# custom-methods/return.rb
1674
+
defgreet_again(cool=false)
1675
+
if cool
1676
+
return greeting ="Yo"
1677
+
end
1678
+
greeting ="Hello"
1679
+
end
1680
+
1681
+
cool =true
1682
+
puts greet_again(cool)
1683
+
```
1684
+
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.
1688
+
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