2

ruby version: 2.3.4

I am fairly new to Ruby and can't figure out why the following code will not update my variable.

class Blah
  attr_accessor :update_me

  def initialize
    @update_me = 6
  end

  def addy
    puts update_me
    if update_me == nil
      update_me = 1
    else
      update_me += 1
    end
  end

end

Here is my input and the results from irb

> a = Blah.new
 => #<Blah:0x007fdcfe819dd0 @update_me=6>

> a.addy
6
NoMethodError: undefined method `+' for nil:NilClass
  from (irb):35:in `addy'
  from (irb):42
  from /Users/tracy/.rvm/rubies/ruby-2.3.4/bin/irb:11:in `<main>'

In my addy method it is clearly seeing the initial value of the update_me variable as 6, and it is passing by the if == nil statement as expected, but when it tries to update the value I get a nil:NilClass error. There is something I appear to be fundamentally misunderstanding here.

tracyjs
  • 21
  • 2

0 Answers0