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

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

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讲师

全部回覆(2)
洪涛

實例方法操作實例變數,有什麼問題?

迷茫

這樣完全沒有問題啊.
容易引起問題的是這種:

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

其中instance_variable_set可以修改物件內的實例變數 ~ ~
當然, 也可以理解為 Ruby 的強大之處!!!

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!