📜  Ruby 中的全局变量

📅  最后修改于: 2022-05-13 01:54:32.978000             🧑  作者: Mango

Ruby 中的全局变量

全局变量具有全局范围,可以从程序中的任何位置访问。从程序中的任何一点分配给全局变量都具有全局意义。全局变量总是以美元符号 ($) 为前缀。如果我们想要一个跨类可用的变量,我们需要定义一个全局变量。默认情况下,未初始化的全局变量具有 nil 值,使用它会导致程序神秘而复杂。全局变量可以在程序中的任何地方更改。
句法 :

$global_variable = 5

例子 :

# Ruby Program to understand Global Variable
  
# global variable 
$global_variable = 10
  
# Defining class
class Class1 
 def print_global 
 puts "Global variable in Class1 is #$global_variable"
 end
end
  
# Defining Another Class
class Class2 
 def print_global 
 puts "Global variable in Class2 is #$global_variable"
 end
end
  
# Creating object
class1obj = Class1.new
class1obj.print_global 
  
# Creating another object
class2obj = Class2.new
class2obj.print_global 

输出 :

Global variable in Class1 is 10
Global variable in Class2 is 10

在上面的例子中,定义了一个全局变量,其值为 10。这个全局变量可以在程序的任何地方访问。
例子 :

# Ruby Program to understand global variable 
$global_variable1 = "GFG"
  
# Defining Class
class Author
  def instance_method
    puts "global vars can be used everywhere. See? #{$global_variable1}, #{$another_global_var}"
  end
  def self.class_method
    $another_global_var = "Welcome to GeeksForGeeks"
    puts "global vars can be used everywhere. See? #{$global_variable1}"
  end
end
  
Author.class_method
# "global vars can be used everywhere. See? GFG"
# => "global vars can be used everywhere. See? GFG"
  
Author = Author.new
Author.instance_method
# "global vars can be used everywhere. See? 
# GFG, Welcome to GeeksForGeeks"
# => "global vars can be used everywhere. See?
# GFG, Welcome to GeeksForGeeks"

输出 :

global vars can be used everywhere. See? GFG
global vars can be used everywhere. See? GFG, Welcome to GeeksForGeeks

在上面的例子中,我们在一个类中定义了两个全局变量。我们创建一个 Author 类的对象,而不是调用方法。