Learn/Ruby/6. Functions
Lesson 6 of 8
Sign in

Ruby, lesson 6

Functions

Once a program grows past a screenful, you start repeating yourself. A method (Ruby's name for a function) lets you write a piece of logic once, give it a name, and use it as often as you like.

Defining and calling a method

def starts the method, then come its name and its parameters in parentheses, then the body, then end. Method names follow the same snake_case rule as variables.

You must define a method before the line that calls it runs, because Ruby reads the file from top to bottom.

Return values

A Ruby method automatically returns the value of the last expression it evaluated. In greet above, that is the string, so there is no need to write return.

Use return when you want to leave a method early:

For a method whose whole body is one expression, Ruby also has a compact "endless" form:

2 exercises to try what you just read.

Exercise 1

Letter grades

Press Ctrl Enter or Check to test your code.

Exercise 2

Shipping cost

Press Ctrl Enter or Check to test your code.

Default and keyword arguments

A parameter can have a default value, used when the caller leaves it out:

Keyword arguments are named at the call site. They make calls with several options much easier to read, and the caller can pass them in any order:

Naming conventions: ? and !

Ruby lets method names end with ? or !. By convention a ? method answers a yes/no question (5.even?, "".empty?) and a ! method does something more drastic than its plain twin, often changing the object itself. Following the same habit in your own code makes it read naturally:

Scope: methods have their own variables

A method cannot see the local variables from outside it. Each method starts with a clean slate that holds only its parameters and whatever it creates itself.

This is stricter than many languages, and it is on purpose: everything a method needs should come in through its parameters. Pass bonus as an argument instead. Constants are the exception; a method can read a constant defined at the top level.

Further reading

  • Ruby docs: Methods
  • Ruby docs: Calling methods

Write a method letter_grade(score) that takes a score from 0 to 100 and returns (not prints) the letter grade:

ScoreGrade
90 to 100A
80 to 89B
70 to 79C
60 to 69D
below 60F

Hidden code reads one score per line, calls your method for each, and prints the results. For the input 95, 72 and 40 on three lines, the output is A, C and F.

A parcel service charges $5 plus $2 for every kilogram. Express delivery doubles the whole price. Write a method shipping_cost(kg, express: false) that returns the cost as an integer.

Hidden code reads lines like 3 or 3 express, calls your method, and prints the result. For example shipping_cost(3) is 11 and shipping_cost(3, express: true) is 22.

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

puts greet("Mira")     # Hello, Mira!
puts greet "Leo"       # parentheses are optional when calling
def safe_divide(a, b)
  return 0 if b == 0
  a / b
end
def square(n) = n * n
def brew(drink = "tea")
  "One #{drink}, coming up"
end

brew            # "One tea, coming up"
brew("coffee")  # "One coffee, coming up"
def order(item, size: "medium", extra_shot: false)
  shot = extra_shot ? " with an extra shot" : ""
  "#{size} #{item}#{shot}"
end

puts order("latte")                              # medium latte
puts order("latte", extra_shot: true, size: "large")
def adult?(age) = age >= 18
bonus = 10

def add_bonus(score)
  score + bonus     # NameError: bonus is not defined here
end