0
0
Rubyprogramming~5 mins

Method declaration with def in Ruby

Choose your learning style9 modes available
Introduction

We use methods to group instructions that do a specific job. This helps us reuse code and keep things organized.

When you want to repeat a task many times without rewriting the code.
When you want to break a big problem into smaller, easier steps.
When you want to give a name to a set of instructions to make your code clearer.
When you want to test parts of your program separately.
When you want to share code with others or use it in different programs.
Syntax
Ruby
def method_name(parameters)
  # code to run
end

The method starts with def and ends with end.

You can give the method a name and add parameters to send information inside.

Examples
A simple method named greet that prints a message.
Ruby
def greet
  puts "Hello!"
end
A method named add that takes two numbers and returns their sum.
Ruby
def add(a, b)
  return a + b
end
A method that takes a name and prints it inside a sentence.
Ruby
def say_name(name)
  puts "Your name is #{name}."
end
Sample Program

This program defines a method called greet that prints a greeting. Then it calls the method to show the message.

Ruby
def greet
  puts "Hello, friend!"
end

greet
OutputSuccess
Important Notes

Methods help avoid repeating the same code many times.

If you don't call the method, the code inside it won't run.

Parameters let you send information to the method to use inside.

Summary

Use def and end to create a method.

Give your method a clear name and add parameters if needed.

Call the method by its name to run the code inside.