some thoughts
is that a little odd – that we have to prefix instance vars with all those @ signs ?
is not - use of - instance members far more common, when using classes ?
is it possible to assume inst.vars inside classes , without prefix ?
some thoughts
is that a little odd – that we have to prefix instance vars with all those @ signs ?
is not - use of - instance members far more common, when using classes ?
is it possible to assume inst.vars inside classes , without prefix ?
The @
symbol denotes that that variable is an instance variable. Just like in Ruby. However there are a few ways to access the instance variables in a class.
Take this for example:
class Foo
property age : Int32 = 1
@name : String = "Jim"
def do_something
user_age = age # Calling the getter for that ivar
self.age = 19 # Calling the setter of that ivar
puts "Hello #{@name}" # Accessing the ivar's value directly
@name = "Fred" # Changing the ivar's value directly
end
end
Not sure if that what you mean?
No, that always assigns to a local variable. You have to do this:
self.age = 19
Oops, fixed.
Ah! I’ve made that mistake a few times, and wondered why it didn’t work the way I was thinking it would. Seems obvious now. In my case I often simply switch back to using the @age
version.
I’m a HUGE fan of @ and @@ to keep track of my scope. It’s one of those things that makes Ruby/Crystal feel Stoner-friendly.
In most APIs you wouldn’t access ivars directly but use getters and setters instead. This allows to implement some custom logic in these methods, should that be required.
So, I think in general, accessing ivars directly should be considered a low-level interface, mostly a hack. For this purpose it’s good to have to prefix each ivar by @
. It should make you wonder, whether you really should access this directly or is there some kind of accessor (or maybe there is a reason not to).
Just use the property
macro and access the variables with a class reference. Calls the @
on the variable internally for you, that’s what I do.
However, if you are wanting to modify a property inside a class, make sure you use @
thanks for input.
it s more clear to me now - seems to have intent.