I was looking through the docs for instance_variable_set and saw that the sample code given does this:
obj.instance_variable_set(:@instnc_var, "value for the instance variable")
which then allows you to access the variable as @instnc_var in any of the class’s instance methods.
I’m wondering why there needs to be a colon : before the @instnc_var. What does the colon do?
My first instinct is to tell you not to use
instance_variable_setunless you really know what you are using it for. It’s essentially a tool for metaprogramming or a hack to bypass visibility of the instance variable.That is, if there is no setter for that variable, you can use
instance_variable_setto set it anyway. It’s far better if you control the code to just create a setter.Try looking at accessors for the vast majority of your instance variable setting needs. They are an idiomatic way to have getters and setters for your instance variables “for free” without you having to write those functions.
If you really do need instance_variable_set, it allows the first argument to be a symbol which is the name of the instance variable to set. A colon is part of the Ruby language that is like a “symbol literal”: when you type
:foo, you’ve created a symbol with value foo, just like when you type"bar"directly into your code, you create a string literal with value “bar”.