← Back to Ruby Course | Chapter 7: Methods | Lesson 1 of 7

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:

  1. Method Basics
Syntax
ruby
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

markup
def greet
  puts "Hello from a method!"
end

greet
greet()
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
  1. Calling a method before its def is executed, which raises NameError in a script because methods are defined as the file runs.
  2. Forgetting end after the body.
  3. Defining def greet with a name that matches a local variable, so greet reads the variable, when greet() with parentheses calls the method.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.