Ruby/Language Basics/Variable scope

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

have two local variables with the same name but in different scopes

def basic_method
  x = 50
  puts x
end
x = 10
basic_method
puts x



items declared in those methods are restricted to those methods.

text = "No worries."
 
def greeting()
  text = "No problems."
  puts text
end
greeting
puts text



Local Variables versus Methods

# If a local variable exists with the same name as a method, 
# the local variable will be referenced 
# unless you put parentheses behind the method or use self.methodName.
def colors(arg1="blue", arg2="red")
    "#{arg1}, #{arg2}"
end
colors = 6
print colors
# The above outputs 6.



Reference an undefined variable in a method

def basic_method
  puts x
end
x = 10
basic_method



using only local variables

def returnFoo
  bar = "Ramone, bring me my cup."
  return bar
end
puts returnFoo
# But this code is not allowed:
def returnFoo
  bar = "Ramone, bring me my cup."
  return bar
end
puts bar