-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmethod_return_value.rb
More file actions
21 lines (16 loc) · 965 Bytes
/
Copy pathmethod_return_value.rb
File metadata and controls
21 lines (16 loc) · 965 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Method return value
# In Ruby, a method can return a value using the `return` keyword. However, if you do not explicitly use `return`, the method will return the value of the last evaluated expression. This means that you can simply place the value you want to return as the last line of the method, and it will be returned when the method is called.
def add(a, b)
a + b # This is the last evaluated expression, so it will be returned
end
result = add(5, 3)
puts result # Output: 8
# You can also use the `return` keyword to return a value from a method. When `return` is executed, it immediately exits the method and returns the specified value.
def division(a, b)
return "Cannot divide by zero" if a.zero? || b.zero? # This will return an error message if either a or b is 0
a / b # This will return the quotient of a and b
end
result = division(10, 2)
puts result # Output: 5
result = division(0, 5)
puts result # Output: Cannot divide by zero