在 Ruby 中,如何在类中编写代码,使 getter foo 和 setter self.foo = ... 看起来更相似? [英] In Ruby, how to write code inside a class so that getter foo and setter self.foo = ... look more similar?

查看:26
本文介绍了在 Ruby 中,如何在类中编写代码,使 getter foo 和 setter self.foo = ... 看起来更相似?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Ruby 中,在类的实例方法中,我们使用 getter by

In Ruby, inside a class's instance method, we use a getter by

foo

我们使用 setter by

and we use a setter by

self.foo = something

一个不需要 self. 而另一个需要,有没有办法让它们看起来更相似,而不是使用类似 self.foo 作为 getter,因为它看起来也很冗长.

One doesn't need to have a self. and the other does, is there a way to make them look more similar, and not using something like self.foo as the getter, as it also looks verbose.

(更新:注意 getter 和 setter 可能只是获取或设置一个实例变量,但它们也可能会做很多工作,比如进入数据库并检查记录是否存在,如果没有,则创建它,等)

(update: note that getter and setter may simply get or set an instance variable, but they might also do a lot of work, such as going into the DB and check the existence of a record and if not, create it, etc)

推荐答案

由于局部作用域优先,当你说 foo = something 时,局部变量 foo 将是创建并分配something的内容.

Since local scope takes precedence, when you say foo = something, a local variable foo will be created and assigned the contents of something.

您可以编写 foo 以使用 getter 的原因是,当 Ruby 找不到具有该名称的变量时,它会在范围内向上移动,并且最终会找到该方法.

The reason you can write foo in order to use the getter is because Ruby will move up in scope when it can't find a variable with that name and it will eventually find the method.

如果有一个与 getter 方法同名的局部变量,Ruby 将使用它的值:

If there is a local variable with the same name as the getter method, Ruby will use its value instead:

class Foo

  attr_accessor :foo

  def initialize
    @foo = :one
  end

  def f
    foo = :two
    foo
  end
end

Foo.new.f
# => :two

为了明确你要访问setter,你必须写self.foo = something.这将告诉 Ruby 您要在 self 对象上以 something 作为参数执行 foo= 方法.

In order to make it clear that you want to access the setter, you must write self.foo = something. That will tell Ruby you want to execute the foo= method on the self object with something as parameter.

这篇关于在 Ruby 中,如何在类中编写代码,使 getter foo 和 setter self.foo = ... 看起来更相似?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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