2017-09-30 32 views
0

我想了解Ruby類以及attr_accessor附帶的自動生成的getter和setter。爲了下面的代碼,我能夠得到它,但沒有設置它?此外,稍後在代碼中設置我的store實例變量(未顯示)。從我read here,它似乎與attr_accessor我應該可以閱讀和寫作。attr_accessor不能用於Ruby類中的變量設置

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

回答

0

什麼attr_accessor:num_filled_buckets給你的兩個方法,一個讀者和作家

def num_filled_buckets 
    @num_filled_buckets 
end 

def num_filled_buckets=(foo) 
    @num_filled_buckets = foo 
end 

返回實例變量@num_filled_buckets一位讀者的方法。 寫入方法需要寫入@num_filled_buckets的參數

我已在下面的類中有一個簡化版本。

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