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
...