is my instance variable being masked?

  • Thread starter Sylvester T Cat
  • Start date
S

Sylvester T Cat

This is probably trivial for the pros here, but

I have a class

class MyClass
attr_accessor :raw_vehicle_data

def parse_raw_vehicle_data
@raw_vehicle_data = [0,1,2,3,4]
puts raw_vehicle_data.size # => gives proper size of the array
(i.e. size > 0)
# do other stuff with raw_vehicle_data
end
end

irb(main):019:0> my_class = MyClass.new
=> #<MyClass:0x00000102005f98>
irb(main):020:0> my_class.parse_raw_vehicle_data
5 #<= this value I expect, but it's not assigned to my "instance
variable"
=> nil
irb(main):021:0> my_class.raw_vehicle_data.size
=> nil

If I change the line from raw_vehicle_data = [0,1,2,3,4] to
@raw_vehicle_data = [0,1,2,3,4], then everything works properly, but I
thought attr_accessor gave me access to the function
"raw_vehicle_data=" that would assign to an instance variable.

Apparently I'm wrong, but not sure why.

Thanks!
 
J

Jeremy Bopp

This is probably trivial for the pros here, but

I have a class

class MyClass
attr_accessor :raw_vehicle_data

def parse_raw_vehicle_data
@raw_vehicle_data = [0,1,2,3,4]
puts raw_vehicle_data.size # => gives proper size of the array
(i.e. size > 0)
# do other stuff with raw_vehicle_data
end
end

irb(main):019:0> my_class = MyClass.new
=> #<MyClass:0x00000102005f98>
irb(main):020:0> my_class.parse_raw_vehicle_data
5 #<= this value I expect, but it's not assigned to my "instance
variable"
=> nil
irb(main):021:0> my_class.raw_vehicle_data.size
=> nil

If I change the line from raw_vehicle_data = [0,1,2,3,4] to
@raw_vehicle_data = [0,1,2,3,4], then everything works properly, but I
thought attr_accessor gave me access to the function
"raw_vehicle_data=" that would assign to an instance variable.

Your code listing above has the @raw_vehicle_data reference, but I think
you meant to leave off the @ there for your problem demonstration.
Leaving off the @ introduces an ambiguity for Ruby in assignment
statements like yours. The left hand side is seen as a local variable
reference rather than a call to the attr_writer method of the same name.

You can either use the @ as you discovered, or you can explicitly call
the attr_writer:

self.raw_vehicle_data = [0,1,2,3,4]

-Jeremy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,969
Messages
2,570,161
Members
46,710
Latest member
bernietqt

Latest Threads

Top