Lesson 12 of 15
Methods
Methods in Ruby
Define a method with def and close it with end:
def greet(name)
puts "Hello, #{name}!"
end
greet("Alice") # Hello, Alice!
Return Values
The last expression in a method is automatically returned — no return keyword needed:
def square(n)
n * n
end
puts square(5) # 25
You can also use return explicitly to exit early.
Default Parameters
Parameters can have default values:
def greet(name, greeting = "Hello")
"#{greeting}, #{name}!"
end
puts greet("Alice") # Hello, Alice!
puts greet("Bob", "Hi") # Hi, Bob!
Your Task
Write a method full_name(first, last, separator = " ") that returns the full name with the separator between first and last.
Print full_name("John", "Doe") and full_name("John", "Doe", "_").
ruby.wasm loading...
Loading...
Click "Run" to execute your code.