I'm trying to use my varialbe in all files of my program. this is an exemple of what I'm tring to do.
我正在尝试在我的程序的所有文件中使用我的varialbe。这是我要做的事情的一个例子。
main.rb
Class1
def self.test1
puts "class 1" if @@debug
end
end
@@ debug = true
class.test1
class.test2
class2.rb
Class2
def self.test2
puts "test2" if @@debug
end
end
I really hope it's enough clear for the community, any help would be appreciated, thanks!
我真的希望它对社区来说足够清楚,任何帮助都会受到赞赏,谢谢!
2 个解决方案
#1
2
You want a global variable or constant. You could create your own, but Ruby conveniently comes with a builtin $DEBUG
global variable. When you specify the -d
option to ruby
, $DEBUG
will be true
, and otherwise, false
.
你想要一个全局变量或常量。你可以创建自己的,但Ruby方便地带有一个内置的$ DEBUG全局变量。为ruby指定-d选项时,$ DEBUG将为true,否则为false。
If the classes are in multiple files, put this in the file that includes the others:
如果类在多个文件中,请将其放在包含其他文件的文件中:
DEBUG=$DEBUG
And in the other files, use DEBUG
for debug, rather than $DEBUG
.
在其他文件中,使用DEBUG进行调试,而不是$ DEBUG。
#2
1
You can create a getter method to get class_variable
您可以创建一个getter方法来获取class_variable
def self.get_debug
@@debug
end
rails however provides a method called cattr_accessor http://apidock.com/rails/Class/cattr_accessor This will allow you to set and get the class variable outside the class
rails然后提供了一个名为cattr_accessor的方法http://apidock.com/rails/Class/cattr_accessor这将允许你设置并获取类外的类变量
i.e. Class1.debug = false
即Class1.debug = false
#1
2
You want a global variable or constant. You could create your own, but Ruby conveniently comes with a builtin $DEBUG
global variable. When you specify the -d
option to ruby
, $DEBUG
will be true
, and otherwise, false
.
你想要一个全局变量或常量。你可以创建自己的,但Ruby方便地带有一个内置的$ DEBUG全局变量。为ruby指定-d选项时,$ DEBUG将为true,否则为false。
If the classes are in multiple files, put this in the file that includes the others:
如果类在多个文件中,请将其放在包含其他文件的文件中:
DEBUG=$DEBUG
And in the other files, use DEBUG
for debug, rather than $DEBUG
.
在其他文件中,使用DEBUG进行调试,而不是$ DEBUG。
#2
1
You can create a getter method to get class_variable
您可以创建一个getter方法来获取class_variable
def self.get_debug
@@debug
end
rails however provides a method called cattr_accessor http://apidock.com/rails/Class/cattr_accessor This will allow you to set and get the class variable outside the class
rails然后提供了一个名为cattr_accessor的方法http://apidock.com/rails/Class/cattr_accessor这将允许你设置并获取类外的类变量
i.e. Class1.debug = false
即Class1.debug = false