0

I was trying to get an understanding of Ruby classes and the auto generated getters and setters that come with attr_accessor. How come for the code below, I'm able to get it but not set it? Moreover, setting works for my store instance variable later in code (not shown). From what I read here, it seems with an attr_accessor I should be ble to read and write.

class HashMap
    attr_accessor :store, :num_filled_buckets, :total_entries

    def initialize(num_buckets=256)
        @store = []
        @num_filled_buckets = 0
        @total_entries = 0
        (0...num_buckets).each do |i|
            @store.push([])
        end
        @store
    end

    def set(key, value)
        bucket = get_bucket(key)
        i, k, v = get_slot(key)

        if i >= 0
            bucket[i] = [key, value]
        else
            p num_filled_buckets # <- this works
            num_filled_buckets = num_filled_buckets + 1 if i == -1 # this does not
            # spits out NoMethodError: undefined method `+' for nil:NilClass
            total_entries += 1
            bucket.push([key, value])
        end
    end
...
Sticky
  • 3,671
  • 5
  • 34
  • 58

1 Answers1

0

What attr_accessor :num_filled_buckets gives you is two methods, a reader and a writer

def num_filled_buckets
  @num_filled_buckets
end

def num_filled_buckets=(foo)
  @num_filled_buckets = foo
end

A reader method that returns the instance variable @num_filled_buckets. A write method that takes an argument which will write to @num_filled_buckets

I've a simplified version of your class below.

class HashMap
  attr_accessor :num_filled_buckets

  def initialize(num_of_buckets=256)
   @num_filled_buckets = 0
  end

  def set
    p num_filled_buckets #calls the reader method num_filled_buckets 
    p @num_filled_buckets #instance variable @num_filled_buckets
    @num_filled_buckets = @num_filled_buckets + 1
    p @num_filled_buckets
  end
end

hm = HashMap.new
hm.set 
# will output
# 0
# 0
# 1
mikej
  • 65,295
  • 17
  • 152
  • 131