Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly set an instance variable with instance_variable_set?

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?

like image 607
you786 Avatar asked Sep 20 '12 02:09

you786


People also ask

How do I assign an instance variable?

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.

How do I set an instance variable in RSpec?

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.

Which is correct about an instance variable?

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.

What is instance variable with example?

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.


1 Answers

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".

like image 104
Matt Avatar answered Oct 06 '22 21:10

Matt