ruby无法保护@变量么?
PHP中文网
PHP中文网 2017-04-22 08:58:46
0
2
497

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

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中文网

认证高级PHP讲师

reply all(2)
洪涛

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

迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!