Ruby类实例变量未在方法调用之间清除:Integer类
我有以下作业代码。经过多次调试,我发现了正在发生的事情Ruby类实例变量未在方法调用之间清除:Integer类,ruby,class,instance-variables,Ruby,Class,Instance Variables,我有以下作业代码。经过多次调试,我发现了正在发生的事情 class Integer def initialize() @ans = "" end def ans @ans = "" end def ans=(value) @ans = value end def to_base(base) # convert given number into the base # figu
class Integer
def initialize()
@ans = ""
end
def ans
@ans = ""
end
def ans=(value)
@ans = value
end
def to_base(base)
# convert given number into the base
# figure out how to make it the most efficient
num = self
r = 0
loop do
r = num % base # modulus
@ans = r.to_s + @ans.to_s # add to answer
num /= base # division
break unless num != 0
end
english = @ans # return value
end
def to_oct
self.to_base(8)
end
end
puts 8.to_oct
puts 8.to_base(2)
输出:
10
100010
二进制版本的输出应该是1000
而不是100010
它所做的是将类的第一个实例8.to\u oct
附加到第二个调用8.to\u base(2)
是否有一种方法可以清除此项,因为我想在本例中使用相同的数字(8),并将其转换为不同的基数。我在课堂上做错了什么
谢谢 要遵循的几个好规则:1)除了在初始值设定项中,不要在代码中引用实例变量。请改用访问器或其他引用。在这门课上,我真的说不出这个变量给你带来了什么好处。2) 不要修补
Integer
或其他Ruby核心类。它们通常是用C实现的,如果您开始重新定义它们的工作方式,它们的行为也不会总是一致的。创建一个新类,改为环绕Integer
。@ZachKemp其他访问器/引用是什么意思?你能给我举一个这样做的好例子吗?@ZachKemp我不同意你的第一点,但第二点对initialize
方法特别重要。@camdixon,这意味着你应该使用方法访问变量,而不是直接引用它们。这使得每个动作都是消息发送的结果,我认为这是面向对象设计的主要特征。而且,Ruby core中的Integer
实际上不是一个类,而是一个方法。