Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessor method is defined but does not work

I have this code:

class A
  attr_accessor :count

  def initialize
    @count = 0
  end

  def increase_count
    count += 1
  end
end

A.new.increase_count

It complains:

in `increase_count': undefined method `+' for nil:NilClass (NoMethodError)

If I change the increase_count definition to:

class A
  def increase_count
    @count += 1
  end
end

then it does not complain. May be I am missing something, or it is just a weird behaviour of Ruby.

like image 870
Ahmad hamza Avatar asked Nov 17 '25 16:11

Ahmad hamza


1 Answers

A#count= requires an explicit receiver as all foo= methods. Otherwise, the local variable count is being created and hoisted, making count + 1 using the local not yet initialized variable.

class A
  attr_accessor :count
  def initialize
    @count = 0
  end

  def increase_count
  # ⇓⇓⇓⇓⇓ THIS 
    self.count += 1
  end
end

puts A.new.increase_count   
#⇒ 1

Sidenote:

attr_accessor :count is nothing but a syntactic sugar for:

def count
  @count
end

def count=(value)
  @count = value
end
like image 179
Aleksei Matiushkin Avatar answered Nov 19 '25 09:11

Aleksei Matiushkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!