Home  >  Q&A  >  body text

ruby无法保护@变量么?

看到一个例子,是有这个问题还是我理解不到位呢?

class LoadPaths
  # ...

  def initialize
    @paths = []
  end
  def push(*paths)
    @paths.push(*paths)
  end
  def inspect
    p @paths
  end
end

a = LoadPaths.new
x = a.push(1)
x.push 2
a.inspect
PHP中文网PHP中文网2712 days ago506

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-22 09:00:46

    Instance methods operate instance variables, what’s the problem?

    reply
    0
  • 迷茫

    迷茫2017-04-22 09:00:46

    There is no problem at all.
    What tends to cause problems is this:

    class A
    
      def count
        @count ||= 0
        @count += 1
      end
    end
    
    a = A.new
    a.count # => 1
    a.instance_variable_set(:@count, 10)
    a.count # => 11
    

    Among theminstance_variable_setyou can modify the instance variables within the object ~ ~
    Of course, it can also be understood as the power of Ruby!!!

    reply
    0
  • Cancelreply