Thuta Learning
BasicProgrammingbeginner

Methods

Relax. We'll talk through this in plain words — no textbook voice.

A method is a named, reusable chunk of code logic. In Ruby, you start a method with def and close it with end. Since a method automatically returns its last expression, you rarely need the return keyword.

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

def add(a, b)
  a + b
end

puts greet("Aung")
puts add(5, 7)

greet takes a name and returns a greeting text. add adds two numbers together and returns the result.

You should see
Hello, Aung! 12

Info

In Ruby methods, if the last line is a value, it's automatically returned.

Easy traps

  • Forgetting to write end is one of the most common syntax errors beginners run into. Remember: whenever you open def, if, class, or do, you need to close it.
Methods | Thuta Learning