Skip to content

Instantly share code, notes, and snippets.

@joshsarna
Created February 25, 2019 20:32
Show Gist options
  • Save joshsarna/4e1dfc74c7848805dd95f41657c27176 to your computer and use it in GitHub Desktop.
Save joshsarna/4e1dfc74c7848805dd95f41657c27176 to your computer and use it in GitHub Desktop.

Methods may or may not have access to certain variables, depending on the circumstances. Here are some examples:

A variable initialized within a method (this works)

def say_hello
  message = "hello"
  return message
end

p say_hello  # => "hello"

A variable initialized outside of a method (this doesn't work)

message = "hello"
 
def say_hello
  return message
end

p say_hello  # => in `say_hello': undefined local variable or method `message' for main:Object (NameError)

An instance variable initialized outside of a method (this works)

@message = "hello"
 
def say_hello
  return @message
end

p say_hello  # => "hello"

A variable initialized outside of a method and passed in as an argument (this works)

message = "hello"
 
def say_hello(input_message)
  return input_message
end

p say_hello(message)  # => "hello
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment