任何方法将ruby中的变量重置为其原始值

时间:2014-10-06 04:52:19

标签: ruby

假设我在@counter=0方法中声明了变量initialize,在我的代码的某些部分,我想再次将其重置为原始值。虽然我可以手动执行@counter=0,但我想知道是否有任何方法可以将其重置为原始分配值。例如:@counter.reset

def initialize
  @counter = 0
  ...
end
def first
  @some_string.each do |f|
    if f == ''
      @counter += 1 
    end
    @counter = 0 # Want to change it here
  end
end

2 个答案:

答案 0 :(得分:3)

如果我理解正确,请尝试:

def initialize
    reset_counter
    ...
end

def reset_counter
    @counter = 0;
end

def First
    @some_string.each do |f|
        if f == ''
            @counter += 1 
        end
    end
    reset_counter
end

答案 1 :(得分:0)

变量不是Ruby中的对象,你不能告诉他们做任何事情。对于变量,您可以做两件事:分配它并取消引用它。