0
0
RubyHow-ToBeginner · 3 min read

How to Create Method in Ruby: Simple Guide with Examples

In Ruby, you create a method using the def keyword followed by the method name and optional parameters. The method ends with the end keyword. Inside the method, you write the code that runs when the method is called.
📐

Syntax

To define a method in Ruby, use the def keyword, then the method name, optional parameters in parentheses, the method body, and close with end.

  • def: starts the method definition
  • method_name: the name you choose for your method
  • parameters: optional inputs inside parentheses
  • end: closes the method definition
ruby
def method_name(parameters)
  # code to run
end
💻

Example

This example shows a method named greet that takes a name and prints a greeting message.

ruby
def greet(name)
  puts "Hello, #{name}!"
end

greet("Alice")
Output
Hello, Alice!
⚠️

Common Pitfalls

Common mistakes include forgetting the end keyword, misspelling the method name, or not passing required parameters.

Also, avoid using parentheses for parameters if you don't have any, but it's allowed.

ruby
def say_hello
  puts "Hello"
# Missing 'end' here causes error

# Correct way:
def say_hello
  puts "Hello"
end
📊

Quick Reference

PartDescription
defStarts method definition
method_nameName of the method
(parameters)Optional inputs to the method
method bodyCode that runs when method is called
endEnds method definition

Key Takeaways

Use def and end to define a method in Ruby.
Method names should be clear and use lowercase with underscores.
Parameters are optional but must be included in parentheses if used.
Always close your method with end to avoid syntax errors.
Call methods by their name and pass arguments if required.