๐ŸŽ“ A1Learner
๐Ÿ”

Ruby Method Scope

Scope is the part of a program where a name can be seen. A method has its own scope, separate from the code around it.

An outside local is not visible inside

The city variable is defined outside the show_city method. The method tries to print city, and the program stops with a NameError.

city = "Oslo"

def show_city
  puts city
end

show_city

An inside local stays inside

The score variable is defined inside the set_score method. The method prints it while it runs, and the name belongs to the method alone.

def set_score
  score = 10
  puts score
end

set_score

A global is shared

The $name variable is a global. The show_name method reads it, and a new value stored outside the method shows in the next call.

$name = "Ana"

def show_name
  puts $name
end

show_name
$name = "Ben"
show_name

Pass the value in as an argument

The show_city method declares a city parameter. The call passes the outside city value in, and the method prints it.

def show_city(city)
  puts city
end

city = "Oslo"
show_city(city)

Example

def add_bonus(score)
  bonus = 5
  score + bonus
end

total = 20
puts add_bonus(total)
puts total

Key points

  • A local variable defined outside a method is not visible inside the method.
  • A local variable defined inside a method stays inside the method.
  • Reading a name outside its scope raises a NameError.
  • A global variable is a name that starts with a $ sign.
  • A global variable can be read and changed anywhere in a program.
  • Pass a value to a method as an argument instead of sharing a global variable.

In this example, the add_bonus method defines its own local named bonus. The call passes the total value in as an argument, and the method returns 25. The last line prints total again, and it still holds 20.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

A method needs a value held in a local variable outside it. What is the clean way to give the method that value?