How-To Geek
Ruby Function (method) Syntax
The Ruby language makes it easy to create functions.
Function Syntax
def functionname(variable)
return <value>
end
Examples
Your function can compute values and store them in local variables that are specific to the function. Those values can then be returned with the return statement.
def say_hello(name)
var = ”Hello, ” + name
return var
end
The return statement also can be shortened for very simple functions into a single line
def say_hello(name)
return “Hello, ” + name
end
You can simplify the function further. The last expression that is evaluated is automatically returned by the method. For example:
def say_hello(name)
“Hello, ” + name
end
This would return the same value as the prior functions.
To call a function
function param1, param2
or
function(param1,param2)
Example
puts say_hello(“Geek”)
|
Subscribe |
Daily Email Updates |
|
You can get our how-to articles in your inbox each day for free. Just enter your email below: |
- By The Geek on 12/31/69
Comments (3)
Comments are closed on this post.
If you'd like to continue the discussion on this topic, you can do so at our forum.
Go to the Forum

If this is “geek” then I am a ballet dancer
lol @punund
Hey good job, Geek. Good to see people making sometimes-difficult-to-grasp concepts clear for those trying to learn to geek.