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?
Values can be assigned during the declaration or within the constructor. Instance variables can be accessed directly by calling the variable name inside the class. However, within static methods (when instance variables are given accessibility), they should be called using the fully qualified name.
If you want to set a controller or view's instance variables in your RSpec test, then call assign either in a before block or at the start of an example group. The first argument is the name of the instance variable while the second is the value you want to assign to it.
Explanation : Instance variables have a default value based on the type. For any non-primitive, including String, that type is a reference to null. Therefore Option B is correct.
When a number of objects are created from the same class blueprint, they each have their own distinct copies of instance variables. In the case of the Bicycle class, the instance variables are cadence , gear , and speed . Each Bicycle object has its own values for these variables, stored in different memory locations.
My first instinct is to tell you not to use instance_variable_set
unless 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_set
to 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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With