2016-03-06 71 views
0

我想知道在ruby中声明变量时场景背后会发生什么。例如,什么区分这些变量彼此?在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" 

回答

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 
0

变量在Ruby中从不声明。当他们第一次被分配时,他们就会出现。

+0

我确信有什么是他们成立的责任。 –

-1

它们的范围区分它们。

相关问题