2016-03-06 72 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

它們的範圍區分它們。

相關問題