实例变量:self vs @ [英] Instance variable: self vs @

查看:101
本文介绍了实例变量:self vs @的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一些代码:

class Person
  def initialize(age)
    @age = age
  end

  def age
    @age
  end

  def age_difference_with(other_person)
    (self.age - other_person.age).abs
  end

  protected :age
end

我想知道的是在age_difference_with方法中使用@ageself.age的区别.

What I want to know is the difference between using @age and self.age in age_difference_with method.

推荐答案

编写@age直接访问实例变量@age.编写self.age告诉对象向自身发送消息age,该消息通常将返回实例变量@age-但根据在给定子类中实现age方法的方式,它可以执行许多其他操作.例如,您可能有一个MiddleAgedSocialite类,该类总是报告其年龄比实际年龄小10岁.或更实际地说,PersistentPerson类可能会从持久性存储中延迟读取数据,并将其所有持久性数据缓存在哈希中.

Writing @age directly accesses the instance variable @age. Writing self.age tells the object to send itself the message age, which will usually return the instance variable @age — but could do any number of other things depending on how the age method is implemented in a given subclass. For example, you might have a MiddleAgedSocialite class that always reports its age 10 years younger than it actually is. Or more practically, a PersistentPerson class might lazily read that data from a persistent store, cache all its persistent data in a hash.

这篇关于实例变量:self vs @的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆