Introduction
In Ruby, every method gives back a result when it finishes. This helps you use that result right away without extra steps.
In Ruby, every method gives back a result when it finishes. This helps you use that result right away without extra steps.
def method_name # some code last_expression end
def add(a, b) a + b end
def greet(name) "Hello, #{name}!" end
def check_even(num) return true if num % 2 == 0 false end
This program defines a method that multiplies two numbers and returns the product. Then it prints the result.
def multiply(x, y) x * y end result = multiply(4, 5) puts "The result is #{result}"
Even if you don't write 'return', Ruby sends back the last thing it did in the method.
If you want to stop and send back a value early, use 'return'.
This feature makes Ruby code shorter and easier to read.
Ruby methods always give back a value automatically.
The last line in the method is what gets returned unless you use 'return' earlier.
This helps you write clean and simple code that flows well.
return statement?return statement to send back a value.return?a + b, which will be returned automatically.def greet(name)
"Hello, #{name}!"
42
end
puts greet("Alice")nil instead. What is the error?def finish puts "Done" end result = finish puts result.inspect
puts returnsputs prints to screen but returns nil.puts "Done" is the last line, method returns nil.puts which returns nil, so method returns nil. -> Option Adef first_non_nil(a, b) # fill in end
a and b.a || b which evaluates to first non-nil value automatically. def first_non_nil(a, b)
return a if a
return b
end uses explicit returns but is longer. def first_non_nil(a, b)
puts a || b
end prints but returns nil. def first_non_nil(a, b)
a
b
end returns b always because last line is b.Pass the test and this pattern moves unknown