Instance @variable vs class @@variable
-
I want to clear something out for me:
When is justified using CLASS variables and when INSTANCE variables? And I don't discuss about evident situations.
I know the difference between this two types... but in some cases it's not so evident which one is more adequate. In more cases, a instance variable, apparently will offer same results like a class variable.
So, my question is what I should take into consideration when I decide the variable scope?
If somebody can offer a clear answer, maybe this will be moved on a Ruby Tutorials section.And please don't laugh on this .
Thanks. -
A very simplified, imperfect, example.
Let's say you have 2 nice, big, powerful Ford F250 pickup trucks. One is bright red. The other is blue.
Class var for all trucks: maxGrossWeight = 3.5 (tons)
Instance var for truck #1: color = red
Instance var for truck #2: color = blue -
@david. said:
A very simplified, imperfect, example.
Let's say you have 2 nice, big, powerful Ford F250 pickup trucks. One is bright red. The other is blue.
Class var for all trucks: maxGrossWeight = 3.5 (tons)
Instance var for truck #1: color = red
Instance var for truck #2: color = blueWell, this is a very simplified explanation about variables, but it doesn't answer my question. For example if I want to make a webdialog interface and I include all my webdialog code inside a class.
class myWebdlg def initialize @my_app_name = 'Test window' @myDlg = UI;;WebDialog.new(@my_app_name, false,"",200, 400, 600, 350, true) @myDlg.set_file( "Example/my_html.html" ) end def showDialog @myDlg.show{} @myDlg.bring_to_front end ...#lot of code... (or cod, if it's about fishes) end #class
In this example, it is OK to have instance variables? And if it is OK, why is? Or, if I'd better make them CLASS variables, why should I do that?
-
It all depends on what you want to do.
Just imagine for instance that you want to offer the possibility to the user to set the size of the dialog boxes. Obviously, you would need to store these 2 parameters, sx and sy, in a place which is independent from the instances of the dialog box.
Also, let's assume you want to keep a list of the dialog boxes opened
You would then define a function
class myWebdlg #Class variables must be declared and initialized in the class @@xsize = 600 @@ysize = 350 @@lst_dlg = [] #Method to set the size(say called from a menu or another part of the application). It also works for dialog box to be created but also for dialog boxes already created and shown. Note that the method must be prefixed by the class name, because it is called regardless of any class instance. def myWebdlg.set_size(sx, sy) @@xsize = x @@ysize = y @@lst_dlg.each { |dlg| dlg.set_size @@xsize, @@ysize } end def initialize @my_app_name = 'Test window' @myDlg = UI;;WebDialog.new(@my_app_name, false,"",200, 400, @@xsize, @@ysize, true) @@lst_dlg.push @myDlg @myDlg.set_file( "Example/my_html.html" ) end def showDialog @myDlg.show{} end end
All dialog box instances would then use the same size when created or if already shown.
That's of course a theoritical example (I am not sure you would have several dialog boxes in reality), but this gives you an idea of why you may need class variables.
Fredo
-
@newone said:
if I want to make a webdialog interface and I include all my webdialog code inside a class.
Don't use a class just because someone once told you that "all code should be OO". This was SmallTalk/Java foolishness. Code should have classes and object instances when it really has classes and object instances.
Ruby doesn't even put class names in a namespace, even classes in a module, so you should avoid classes unless there is some compelling reason to have them.
-
@martinrinehart said:
so you should avoid classes unless there is some compelling reason to have them.
Well, Mr. Martin Rinehart... it seems that a lesson about "right way of coding" is necessary. I just don't know who will provide one. When should we use classes and when we can stick just on modules. This is what made me undertand modules: http://www.rubyfleebie.com/an-introduction-to-modules-part-1/
-
@newone said:
if I want to make a webdialog interface and I include all my webdialog code inside a class.
That's the right way to do it in Ruby.
@martinrinehart said:
Don't use a class just because someone once told you that "all code should be OO". This was SmallTalk/Java foolishness. Code should have classes and object instances when it really has classes and object instances.
Classes are simple and straightforward in Ruby, even if you plan to use only one instance. The method invokation is very natural
class.method(arguments)
, and it allows to encapsulate variables and method names in the class namespace.@martinrinehart said:
Ruby doesn't even put class names in a namespace, even classes in a module, so you should avoid classes unless there is some compelling reason to have them.
As far as I know, classes are attached to their encapsulating module. They provide their own namespace and live in the module namespace too (just try to type
Entities
in the Ruby console, and thenSketchup::Entities
to see the difference).Fredo
-
I've got an example that helped me understand the class vs instance variable situation a little better.
If you have ever made a true "tool" in SketchUp, you would have made it its own class. So for example, my line tools plugin makes a line tools class. That class gets instantiated each time the user runs the plugin. I had used instance variables to remember the last line length entered by the user, so that the tool would rememeber the user's last input. But it only remembered their input while the tool weas active. Once they switched over to the select tool, and then back to my plugin, their input was lost because it was stored in an instance variable. So I switched them all to class variables. Then once they input something, that class variable would stay alive during their entire SU session.
Did that make sense and help at all?
Chris
-
@unknownuser said:
Classes are simple and straightforward in Ruby
That's certainly true, but please explain why:
class MyUniqueName # funcs and vars here end
is better than:
module MyUniqueName # funcs and vars here end
-
Martin,
A Class allows to create instances, which are designated by variables, so very easy to manipulate.
It is also a good way to encapsulate an interface (what SU does with the Sketchup::Tool placeholder class)
Within theclass
statement, you can declare methods with their name, without any prefixing.Personally, I always declare classes within modules. Classes is a way to manipulate objects, whereas module is a way to package the script and provide privacy via a namespace.
Fredo
-
For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.
module MyMod @var = 1 def MyMod.one @var # <- this is the same @var end def self.two @var # <-- the same @var end end
Even if the module is split across files.
# File1.rb module MyMod @var ||= 1 def MyMod.one @var ||= 2 p @var end end #File2.rb module MyMod @var ||= 3 def MyMod.two @var ||= 4 p @var end end
Technically, instance variables are bound to self, so you need to be able to resolve what object is self to know which instance variables are in scope.
I think a class variable will have the same visibility when used the same way in a module, but for a different reason.
-
@unknownuser said:
Within the
class
statement, you can declare methods with their name, without any prefixing.I find Ruby's insistence on
self.xxx
to define module-level functions is quite a nuisance. On the other hand, if you create a singleton instance of your class, then to manipulate anything you have toinstance.xxx()
whereas in the module you can call your functions without a prefix.In practice, both my Rubies have used classes within modules but that's because I converted original module-less code to module-enclosed code, classes and all.
-
@jim said:
For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module....
Even if the module is split across files.
Didn't know that you could have instance vars in modules, nor that you could split modules across files. Thanks.
-
@martinrinehart said:
Didn't know that you could have instance vars in modules, nor that you could split modules across files. Thanks.
It's one Ruby's hallmark features (for better or worser) - you can re-open a class at any time and add to it, or redefine what's there.
-
@jim said:
For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.
I think a class variable will have the same visibility when used the same way in a module, but for a different reason.
Before starting this post (and that was the reason for the post), I had some problems with instance/class variables. I noticed that instance variables act something like "globals" inside a module, but something strange happened with class variables. I could not acces class variables from outside class. I am not sure yet what was the cause...
-
As I leaned since now, in ruby, variables don't store data, instead they are pointing to value. But I don't know if class variables have pointers or not? Do they are static or dynamic?
-
Boy, a lot of topics in this thread. Here's an old programmer's brief thoughts...
Why use Classes - Use classes when 'things' have data/properties. I have code that exports faces from SU to a text file. One format requires all the coordinates be listed together (with an ID) in the text file. My code loops thru the faces and creates an object from each face, with layer, material, etc and coordinate info as instance variables. The loop code creates a few hashes for the coordinates; the face objects can reference that after it's created. If I didn't use classes, I'd be screwing around with crazy arrays and all sorts of stuff. Years ago, that's how one had to code, B4 OOP.
Class vs Instance - Using the above example, I use class variables for switches that affect all the objects, like what data to export. Also, the coordinate hashes are class variables.
All of my web dialogs are classes, not because I create a lot of them, but because the class holds data. Both data for the dialog, and data that exists after a modal dialog is closed, like the choices a user picked.
Keep in mind that classes are very generic and designed so that the user can't get at the internals. That's what setters/getters are for, so the designer, if needed, can validate changes made by an object's user.
HTH,
Greg
-
@newone said:
@jim said:
For a typical plugin that uses a module strictly as a namespace, an instance variable (@anytyhing) can be thought of as "global" within the module.
I think a class variable will have the same visibility when used the same way in a module, but for a different reason.
Before starting this post (and that was the reason for the post), I had some problems with instance/class variables. I noticed that instance variables act something like "globals" inside a module, but something strange happened with class variables. I could not acces class variables from outside class. I am not sure yet what was the cause...
You shouldn't be able to access class variables outside a class (object instance) without using an accessor (a reader and/or writer). Same goes for instances variables. That's part of the reason for using classes. There really are no global variables except true global variables (eg, using '$' as the first character of the name). And, Module vars are not globally scoped, they are Module scope only.
Class vars are visible (or shared) to all object instances of a class. Instance vars are visible only to a specific object instance of a class. That is why I gave the simple example using the truck above. Neither is visible outside an object instance without an accessor (using either a class method or attribute accessor).
You should check out the freely available online doc... Programming Ruby for more details about classes and variables in Ruby.
-
@martinrinehart said:
@unknownuser said:
Within the
class
statement, you can declare methods with their name, without any prefixing.I find Ruby's insistence on
self.xxx
to define module-level functions is quite a nuisance. On the other hand, if you create a singleton instance of your class, then to manipulate anything you have toinstance.xxx()
whereas in the module you can call your functions without a prefix.You don't need to prefix methodnames in modules. Use a class << self block wrapper around all the methods inside the module.
See my post: [info] Using Ruby Modules
Advertisement