It really comes down to what the intended use of the class is, and whether the value should be instance dependent or not. There are valid use cases for each, it’s not really a use x over y type of situation.
In this case, if the goal is to just double a number, a class isn’t really needed in the first place as you could just do my_num * 2. However for demo purposes, i could probably go with like
class MyClass
def self.double(value : Int32)
value * 2
end
end
The reasoning being the class is essentially just being used as a namespace, really a module might be a better option for this case. Also depends on the context of how this class/object is being used.
I think the question was more “when should I use var vs. @var inside a method”.
My answer is: both are the same. Choose whichever you prefer. var is shorter. It also allows being redefined by subclasses but it usually doesn’t matter.
Also performance is exactly the same in both cases.
@asterite, @Blacksmoke16 : yes, that was the meaning of my question, and, of course, I should have written instance variable, not class variable. Interesting to know performance is the same for either syntax.
Yes, because var += 1 is expanded to var = var + 1, so an assignment expression. And assignment expressions create local variables, shadowing any method. To disambiguate this you need to do self.var += 1.