Ruby 变量学习笔记
变量是编程中非常重要的概念,Ruby 也不例外。在 Ruby 中,变量分为局部变量、实例变量、类变量和全局变量四种类型,下面将详细介绍各种变量的定义和使用。
局部变量(Local Variables)
局部变量是定义在方法内部或块内部的变量,只能在它所在的方法或块内使用。局部变量以小写字母或下划线开头。
定义局部变量
rubyCopy Codedef test
message = "Hello, world!"
puts message
end
test # => Hello, world!
访问局部变量
rubyCopy Codedef test
message = "Hello, world!"
puts message
end
test # => Hello, world!
puts message # => NameError: undefined local variable or method `message'
实例变量(Instance Variables)
实例变量属于类的实例(对象),可以在类的任何地方使用。实例变量以 @ 符号开头。
定义实例变量
rubyCopy Codeclass Person
def initialize(name)
@name = name
end
def say_hello
puts "Hello, my name is #{@name}."
end
end
person = Person.new("Alice")
person.say_hello # => Hello, my name is Alice.
访问实例变量
rubyCopy Codeclass Person
def initialize(name)
@name = name
end
def say_hello
puts "Hello, my name is #{@name}."
end
end
person = Person.new("Alice")
puts person.@name # => SyntaxError: unexpected '.', expecting end-of-input
类变量(Class Variables)
类变量属于类,可以由该类的所有实例或对象共享。类变量以 @@ 符号开头。
定义类变量
rubyCopy Codeclass Person
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def self.count
@@count
end
end
person1 = Person.new("Alice")
person2 = Person.new("Bob")
puts Person.count # => 2
访问类变量
rubyCopy Codeclass Person
@@count = 0
def initialize(name)
@name = name
@@count += 1
end
def self.count
@@count
end
end
puts Person.@@count # => SyntaxError: class variable @@count not defined for Person
全局变量(Global Variables)
全局变量可以在任何地方被访问,但是应该避免使用全局变量,因为它们会在不同地方产生意想不到的副作用,引起错误。全局变量以 $ 符号开头。
定义全局变量
rubyCopy Code$debug = true
def foo
puts "Debug mode is on." if $debug
end
foo # => Debug mode is on.
访问全局变量
rubyCopy Code$debug = true
def foo
puts "Debug mode is on." if $debug
end
puts $debug # => true
以上就是 Ruby 变量的学习笔记,希望可以帮助你更好地理解 Ruby 中各种变量的定义和使用。