ruby - 带有访问器的 `self` 的遗漏

标签 ruby self accessor

当通过访问器方法attribute 访问实例变量时,表达式self.attributeattribute 有什么区别?比方说,我们定义了一个访问器:

def post
  @post
end

我们可以打电话

self.post

或者只是

post

添加self有什么特别之处?

最佳答案

当可能存在隐藏方法调用的局部变量时,情况会有所不同。使用 self 允许我们指定我们想要的方法,而不是本地变量。看一个例子:

class Foo
  def post
    @post
  end

  def post= (content)
    @post = content
  end 

  def test
    #difference 1 
    p post # >> nil

    @post = 10
    p post # >> 10

    post = 42
    p post # >> 42
    p self.post # >> 10

    #difference 2
    # assign to @post, note that you can put space between "self.post" and "="
    self.post = 12 

    #otherwise it means assigning to a local variable called post.
    post = 12
  end
end

Foo.new.test

关于ruby - 带有访问器的 `self` 的遗漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14602052/

相关文章:

ruby - Class.superclass = 模块,Module.class = 类?

python - self 做什么?

Swift 更新标签(带有 HTML 内容)需要 1 分钟

Kotlin 会自动生成 Getter 和 Setter,但为什么?

html - 忽略用 y 关闭 x 的尝试

ruby - Jekyll 默认使用系统 Ruby 版本而不是 RVM 版本

Python 类 self.variables

c++ - 基于 C++ 类中的参数查看私有(private)变量的访问器方法?

laravel - Laravel 中的修改器和访问器是什么

ruby - 在 Ruby 1.9 中使用 eval() 测试 Ruby 代码片段