English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Variablen sind Speicherorte, die Daten speichern, die von jedem Programm verwendet werden können.
Ruby unterstützt fünf Arten von Variablen.
Allgemein kleine Buchstaben, Unterstriche beginnend: Variable (Variable).
Mit $ beginnend: Globale Variable (Global variable).
Mit @ beginnend: Beispielvariable (Instance variable).
Mit @@ beginnend: Klassenvariable (Class variable) Klassenvariablen werden im gesamten Vererbungsbaum gemeinsam genutzt
Großbuchstaben am Anfang: Konstante (Constant).
Sie haben diese Variablen in den vorangegangenen Kapiteln grob kennengelernt. In diesem Kapitel werde ich Ihnen diese fünf Arten von Variablen im Detail erläutern.
Globale Variablen beginnen mit $. Der Wert einer nicht initialisierten globalen Variable ist nilbei der Verwendung -W Option führt zu einer Warnung.
Das Zuweisen von Werten zu globalen Variablen ändert den globalen Zustand, daher wird empfohlen, globale Variablen nicht zu verwenden.
Nachstehende Beispiele zeigen die Verwendung von globalen Variablen.
#!/usr/bin/ruby # -*- coding: UTF-8 -*- $global_variable = 10 class Class1 def print_global puts "Globale Variable in Class1 wird ausgegeben als #$global_variable" end end class Class2 def print_global puts "Globale Variable in Class2 wird ausgegeben als #$global_variable" end end class1obj = Class1.new class1obj.print_global class2obj = Class2.new class2obj.print_global
Hier ist $global_variable eine globale Variable. Dies führt zu folgendem Ergebnis:
Hinweis:In Ruby können Sie durch das Platzieren eines # Zeichens vor einer Variable oder Konstanten den Wert jeder Variable oder jeden Konstanten abrufen.
Globale Variable in Class1 wird ausgegeben als 10 Globale Variable in Class2 wird ausgegeben als 10
Beispielfaktoren beginnen mit @. Der Wert eines nicht initialisierten Beispielfaktors ist nilbei der Verwendung -W Option führt zu einer Warnung.
Nachstehende Beispiele zeigen die Verwendung der Beispielfaktoren.
#!/usr/bin/ruby class Customer def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id @cust_id" puts "Customer name @cust_name" puts "Customer address @cust_addr" end end # Create object cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call method cust1.display_details() cust2.display_details()
Hier sind @cust_id, @cust_name und @cust_addr Beispielfaktoren. Dies führt zu folgendem Ergebnis:
Kundenid 1 Kundenname John Kundenadresse Wisdom Apartments, Ludhiya Kundenid 2 Kundenname Poul Kundenadresse New Empire road, Khandala
Klassenvariablen beginnen mit @@ und müssen initialisiert werden, bevor sie in Methodendefinitionen verwendet werden können.
Verwenden Sie eine nicht initialisierte Klassenvariable führt zu einem Fehler. Klassenvariablen können in den Subklassen oder Submodulen der Klasse oder des Moduls, in dem sie definiert sind, gemeinsam genutzt werden.
In use -After the w option, redefining class variables will generate a warning.
The following example demonstrates the usage of class variables.
#!/usr/bin/ruby class Customer @@no_of_customers=0 def initialize(id, name, addr) @cust_id=id @cust_name=name @cust_addr=addr end def display_details() puts "Customer id @cust_id" puts "Customer name @cust_name" puts "Customer address @cust_addr" end def total_no_of_customers() @@no_of_customers += 1 puts "Total number of customers: #@@no_of_customers" end end # Create object cust1=Customer.new("1", "John", "Wisdom Apartments, Ludhiya") cust2=Customer.new("2", "Poul", "New Empire road, Khandala") # Call method cust1.total_no_of_customers() cust2.total_no_of_customers()
Here, @@no_of_customers is a class variable. This will produce the following result:
Total number of customers: 1 Total number of customers: 2
Local variables start with lowercase letters or an underscore _. The scope of local variables extends from class, module, def, or do to the corresponding end or from the left curly brace {} to the right curly brace {}.
When calling an uninitialized local variable, it is interpreted as calling a method without any parameters.
Assigning to an uninitialized local variable can also be treated as a variable declaration. The variable will exist until the end of the current scope. The lifecycle of local variables in Ruby is determined during the parsing of the program.
In the above example, the local variables are id, name, and addr.
Constants start with uppercase letters. Constants defined within a class or module can be accessed from within the class or module, while constants defined outside of a class or module can be accessed globally.
Constants cannot be defined within methods. Assigning to an uninitialized constant will raise an error. Assigning to an already initialized constant will raise a warning.
#!/usr/bin/ruby # -*- coding: UTF-8 -*- class Example VAR1 = 100 VAR2 = 200 def show puts "The value of the first constant is #{VAR1" puts "The value of the second constant is #{VAR2" end end # Create object object=Example.new() object.show
Here, VAR1 and VAR2 is a constant. This will produce the following result:
The value of the first constant is 100 The value of the second constant is 200
They are special variables that have the appearance of local variables, but behave like constants. You cannot assign any values to these variables.
self: The receiver object of the current method.
true: Represents the value of true.
false: Represents the value of false.
nil: Represents the value of undefined.
__FILE__: The name of the current source file.
__LINE__: The line number in the source file.