Method Basics
A method is a named recipe you write once and use whenever you want. In Ruby you start with def and finish with end.
In this page:
Syntax
def method_name
# body
end
method_name
Method Basics
A Ruby method is defined with def method_name ... end, and called by its name, with or without parentheses depending on context.
Method names conventionally use snake_case, and by convention, a method ending in ? returns a boolean while one ending in ! performs a mutating or "dangerous" operation. Every method returns a value, either explicitly via return or implicitly as the value of its last expression.
Note:
Parentheses around method arguments are optional in Ruby, but idiomatic style generally includes them for methods that take arguments.
Example: Method Basics
def greet
puts "Hello from a method!"
end
greet
greet()
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Calling a method before its
defis executed, which raisesNameErrorin a script because methods are defined as the file runs. - Forgetting
endafter the body. - Defining
def greetwith a name that matches a local variable, sogreetreads the variable, whengreet()with parentheses calls the method.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: