Feeling Included : attr_accessor returning nil


#1

Why does this code return a nil instead of the value of @ax? Does the attr_accessor reading and writing capabilities only relate to setting the variable's value outside the class?

Test code:
class Person
attr_accessor :ax
@ax = "1"
end

bob = Person.new
print bob.ax #returns nil


#2

Why does this code return a nil instead of the sring?

Test code:
class Person
attr_accessor :ax
@ax = "1"
end

bob = Person.new
print bob.ax #returns nil

This is how print is defined. See here:
http://ruby-doc.org/core-2.4.0/Kernel.html#method-i-print

Just being curious: why did you expect that it would return the string?

Ronald


#3

class Person
  attr_accessor :ax 
end

bob = Person.new
bob.ax = '1'
print bob.ax

To set and instance variable I believe you may need a setter. Over to someone who has more insight into this...


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.