Methods
Collapse Content
Show Content
Methods
Ruby methods are powerful and easy-to-use. This is their syntax:
def method_name end
Here's a basic method with one parameter:
def double(x)
x * 2
end
Methods (and blocks) implicitly return the value of the last statement
double(2) #=> 4
You can also use an explicit return:
def square(x)
return x * x
end
Parentheses are optional where the result is unambiguous
double 3 #=> 6
double double 3 #=> 12
Multiple Parameters are separated with commas:
def sum(x,y)
x + y
end
...and commas are used again when calling the method:
sum 3, 4 #=> 7
Please sign in or sign up to submit answers.
Alternatively, you can try out Learneroo before signing up.