在Ruby中声明变量时,后台会发生什么?

时间:2016-03-06 13:14:29

标签: ruby variables

我想知道在ruby中声明变量时场景背后会发生什么。例如,这些变量之间的区别是什么?

#normal variables
name = "John"

#instant variables
@name = "John"

#class variables
@@name = "John"

#class instance variables
def self.namer
   @name = "John"
end

#constants
NAME = "John"

3 个答案:

答案 0 :(得分:2)

正常变量,如name,是本地变量。它们仅在声明它们的范围内可用。

class Dog
  def set_a_variable
    name = "Fido"
  end
  def show_a_variable
    name
  end
end

my_dog = Dog.new
my_dog.set_a_variable
my_dog.show_a_variable
=> NameError: undefined local variable or method `name'

实例变量(如@name)属于类的实例,因此类实例的每个实例方法都可以访问该变量。如果未设置,则假定为nil

class Dog
  def set_a_variable
    @name = "Fido"
  end
  def show_a_variable
    @name
  end
end

my_dog = Dog.new
my_dog.set_a_variable
my_dog.show_a_variable
=> "Fido"
my_second_dog = Dog.new
my_second_dog.show_a_variable
=> nil # not shared between different instances

类变量(如@@legs)可以被类的所有实例访问,因此每个实例都可以访问该变量。它们也是由子类继承的。

class Animal
  def set_a_variable
    @@legs = 4
  end
end

class Dog < Animal
  def show_a_variable
    @@legs
  end
end

my_animal = Animal.new
my_animal.set_a_variable
my_dog = Dog.new
my_dog.show_a_variable
=> 4
my_second_dog = Dog.new
my_second_dog.show_a_variable
=> 4

类实例变量(类方法中定义的@name)属于特定类,因此每个实例方法都可以访问该变量,但它不会被子类继承。

class Animal
  def self.set_a_variable
    @legs = 2
  end
  def self.show_a_variable
    @legs
  end
  def show_a_variable
    self.class.show_a_variable
  end
end

class Dog < Animal
  def self.set_a_variable
    @legs = 4
  end
end

my_dog = Dog.new
Dog.set_a_variable
my_animal = Animal.new 
Animal.set_a_variable
my_dog.show_a_variable
=> 4

常量不是全局的,但可以通过任何地方的范围访问。

class Animal
  LEGS = 4
end

class Dog
  def show_a_variable
    Animal::LEGS
  end
end

my_dog = Dog.new
my_dog.show_a_variable
=> 4

答案 1 :(得分:0)

永远不会在Ruby中声明变量。它们刚刚被分配时就会存在。

答案 2 :(得分:-1)

他们的范围区别于他们。