0

I'm trying to use my variable in all files of my program. this is an example of what I'm trying to do.

 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 Answers 2

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.

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.

Sign up to request clarification or add additional context in comments.

9 Comments

i want a global variable but in the other file it doesn't work --"
@TakezoShinmen: And how are you connecting these files? Require? Nothing will work without require.
@TakezoShinmen: Show me the require.
Maybe it is not clear enough, that you do not need to build your own debug mechanism. simply check for $DEBUG and run your program with ruby -d prog.rb when you want the debug output and with ruby prog.rb when you don't want it. No need for class variables etc.
@Linuxios these are my require: require 'qark_stat',require 'qark_matrix' padde i have to create $DEBUG and only type -d for using it ?
|
1

You can create a getter method to get 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

i.e. Class1.debug = false

1 Comment

,I try it but i have an undifined method :s

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.