Ruby 实例变量访问 [英] Ruby instance variable access

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

问题描述

只是想知道在设置了 attr_accessor 的情况下从类中访问实例变量的最佳实践是什么.

Just curious what the best practice is for accessing an instance variable from within a class assuming attr_accessor is set.

class Test
  attr_accessor :user

  def initializer(user)
    @user = user
  end

  def foo
    @user
  end
end

class Test
  attr_accessor :user

  def initializer(user)
    @user = user
  end

  def foo
    self.user
  end
end

那么通过实例变量(@user)还是getter方法(Test#user)?

So by instance variable (@user) or getter method (Test#user)?

推荐答案

Getter 方法,因为它更容易重构.假设您想在访问点更新时间戳.

Getter method, because it's easier to refactor. Say you want to update a time stamp at the point of access.

class Test
  def user
    @user.last_read = Time.now
    @user
  end
end

并且您对 user 的所有引用都使用新逻辑进行了更新.如果您引用的是 @user,就不是那么容易了.

And all your references to user are updated with the new logic. Not so easy if your references are to @user.

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

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