Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby instance_variable_get returns nil

I've a problem with the instance_variable_get method cause it's always returns nil object with one of my object instance. Here is my code:

logger.info "ASDF: " + @d_tree.inspect
logger.info "ASDF: " + @d_tree.instance_variable_get(:@content);

and the output is:

ASDF: #<DTree id: 11, parent_id: nil, content: "bababababa", subsidiary_info: "", deep_info: "blabla", title: "hello", direction: 1, created_at: "2010-10-26 19:27:32", updated_at: "2010-11-01 23:14:31", color: 2, cell_color: 2, howtoinfo: "howtoinfooo", textinfo: "textInfooo", locationinfo: "locationInfoooo", productinfo: "productinfoooo">
TypeError (can't convert nil into String):
    /app/controllers/d_trees_controller.rb:38:in `+'

According to the inspect the object seems to be fine, but the instance_variable_get returns a nil object

Thanks for your help!

like image 767
seriakillaz Avatar asked Nov 02 '10 13:11

seriakillaz


2 Answers

instance_variable_get(arg)

It should return the value of the instance variable or nil if the instance variable is not set.

for example

we define the following class

  class Velpradeep
    def initialize(mark1, mark2)
      @m, @s = mark1, mark2
    end
end

During creation of the object of the class

obj = Velpradeep.new(98,96)

Then we can access the instance variables by using :

irb(main):046:0> obj.instance_variable_get(:@m)
=> 98

Access the undefined instance variables defined in the initialize method

irb(main):047:0> obj.instance_variable_get(:@p)
=> nil # provides nil bcz the instance variable is not defined 

If you want to access the variable before you need to set the instance variable using

instance_variable_set()

example :

irb(main):048:0> obj.instance_variable_set(:@p, 99)
=> 99

Then we can use, it will return the value of the instance variable....

irb(main):049:0> obj.instance_variable_get(:@p)
=> 99
like image 141
vel pradeep.MS Avatar answered Nov 02 '22 15:11

vel pradeep.MS


Although it's considered bad form to grab instance variables like this directly, as using attr_accessor is the preferred method, the problem in this particular instance is that there is no instance variable called @content. What you have appears to be an ActiveRecord attribute.

These are fetched using a different mechanism:

@d_tree.attributes[:content]

Generally this is even a little redundant as this will needlessly create a copy of the attributes hash. The typical way to access is:

@d_tree.content

These values are actually located in the @attributes instance variable managed by ActiveRecord.

like image 38
tadman Avatar answered Nov 02 '22 16:11

tadman