balthatrix balthatrix - 1 year ago 62
Ruby Question

Setting with accessors in initialize results in nil properties

Why does the last line result in nil and not


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

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

def initialize
@thing1 = 15

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download