Skip to content
Justice Tech School

Methods and Blocks

Define methods with def and end. The last expression is returned automatically. Parameters can have defaults and keyword arguments. Blocks and yield let callers pass code in.

Example
def greet(name = "friend", punctuation: "!")
  "Hello, #{name}#{punctuation}"
end
puts greet, greet("Ada"), greet("Tunde", punctuation: "?")
def twice
  yield
  yield
end
twice { puts "block runs" }
square = ->(x) { x * x }
puts square.call(7)

Result

Hello, friend!
Hello, Ada!
Hello, Tunde?
block runs
block runs
49

Exercise

Define a method.

 hello
  "hi"
end

Quiz Test

What does a method return by default?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.