使用“ attr_accessor”定义非标准的访问器方法

时间:2018-10-23 03:12:35

标签: ruby

我想知道是否可以使用attr_accessor来引用名称与其定义的方法不同的属性。例如,我有一个带有属性GameWindow的类bg_color,并且我想attr_accessor定义方法backgroundbackground=。有什么方法可以做,还是我必须自己定义方法?

4 个答案:

答案 0 :(得分:2)

您希望attr_accessor定义方法background和background =。 attr_accessor用于定义实例的getter和setter,变量&method是返回值的东西,但您不能像method的background =那样使用setter。

请与alias_attributealias_method进行确认。

答案 1 :(得分:1)

attr_accessor creates the instance variable(此处为@bg_color;或更精确地说,可以调用该对象,尽管正如Cary和Jörg在下面指出的那样,实例变量不是严格创建,直到被分配为止)以及以您使用的符号参数命名的读写器方法。如果您希望将其命名为background,为什么不直接更改名称呢?

答案 2 :(得分:1)

attr_accessor :background

只是一个简单的宏,可以为您生成以下两种方法:

def background
  @background
end

def background=(value)
  @background = value
end

当您要使用特定名称的getter和setter方法但将值分配给具有不同名称的变量时,只需自己编写方法-例如:

def background
  @bg_color
end

def background=(value)
  @bg_color = value
end

答案 3 :(得分:1)

attr_accessoralias_method结合使用。例如:

class Foo
  attr_accessor :bar

  alias_method :baz, :bar
  alias_method :baz=, :bar=

  def initialize
  end
end

然后验证它是否按预期工作:

foo = Foo.new
=> #<Foo:0x00007fabb12229a0>
foo.bar = 'foobar'
=> 'foobar'
foo.baz
=> 'foobar'
foo.baz = 'barfoo'
=> 'barfoo'
foo.bar
=> 'barfoo'
相关问题