我试图了解Ruby类以及attr_accessor
附带的自动生成的getter和setter。为什么下面的代码,我能够得到它但没有设置它?此外,稍后在代码(未显示)中设置适用于我的store
实例变量。从read here开始,似乎attr_accessor
我应该阅读和写作。
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 :(得分: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的reader方法。 一个write方法,它接受一个将写入@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