There's no reason (that I can see from your question) that @unit_sz
needs to be an instance variable — you can just treat it as a method. There are instances where you might want to set an ivar (caching, memoization, etc), but for this simple case, unit_sz
should be:
def unit_sz
unit_rows * unit_cols
end
Note that this method uses accessors instead of accessing the instance variables directly. In general this is good practice, as the values are the result of message sends, which you could take advantage of as you grow or extend the class. Instance variables should be set in initialize
or in their individual setters, but usually nowhere else.
In iterating over all of your instance variables, you are essentially creating a custom inspect
method, but one in which you don't know beforehand what instance variables you have defined. The trouble here is that you have a confluence of behavior and data. The structure of the class (its instance variables and methods) should define the behavior and the variables should hold the data, but here, since you have a variable number of variables, the structure of any particular instance is leaning toward the data side. If you need an arbitrary number of key-value pairs, use a hash instead. I don't think you do, however, since the @unit_sz
problem has already been taken care of.
As for your last question, you seem to be defining a static variable (i.e., no getters or setters, so only the value you define in your class). You can either use a constant (MY_VAR = 5
), or a private method (which I prefer):
class Unit
private
def my_var
5
end
end