balthatrix balthatrix - 6 months ago 8
Ruby Question

Setting with accessors in initialize results in nil properties

Why does the last line result in nil and not

15
?

class TextC
attr_accessor :thing1
def initialize
thing1 = 15
puts "thing: #{thing1}"
end
end
tc = TextC.new
# thing: 15
# => #<TextC:0x007fe5617f1b30>
tc.thing1
# => nil


When
initialize
is as below (using the
@
notation), it successfully sets:

def initialize
@thing1 = 15
end

Answer

attr_accessor :thing1 defines an attribute that accesses the instance variable @thing1. Instance variables are always prefixed with an @.

Assigning thing1 = 15 creates a local variable within the initialize method. It does not set the value of the instance variable @thing1. Because @thing1 has not been assigned, the attribute reader tc.thing1 will return nil.

To call the attribute writer from an instance method, you can use self.thing1 = 15. The attribute writer will then assign the @thing1 instance variable.

Comments