我试图理解 ruby 编程语言中的 "Getters" 和 "Setters"

Im trying to understand "Getters" and "Setters" in the ruby programming language

我目前正在做一些关于 ruby 编程语言的在线教程,我认为到目前为止我得到的 explanations/examples 是缺乏的。在直接问这个问题之前,我想给你看两个例子。

第一个例子是:

繁体Getters/Setters;

class Pen

  def initialize(ink_color)
    @ink_color = ink_color # this is available because of '@'
  end

  # setter method
  def ink_color=(ink_color)
    @ink_color = ink_color
  end

  # getter method
   def ink_color
    @ink_color
  end

end

第二个例子是:

ShortCutt Getter/Setters;

class Lamp
  attr_accessor :color, :is_on

  def initialize(color, is_on)
    @color, @is_on = color, false
  end
end

好的,对于第一个示例,我认为它非常简单。我是 'initializing' 整个 Lamp class 中的一个可访问变量,称为“@ink_color”。如果我想将“@ink_color”设置为红色或蓝色,我只需调用我的 'Setter' 方法并将 'red' 或 'blue' 传递给参数(ink_color ) 在我的 setter 中。然后如果我想访问或 'Get/Getter' 我有 'Set/setter' 的颜色,我会调用我的 getter 方法并请求 'ink_color'。

第二个例子对我来说也很有意义; getter 和 setter 方法不是输入什么,而是 ruby 提供了一个 'shortcut',它本质上运行代码来构建 getter 和 setter 给你。

但问题来了——如何对 'shortcut' 版本进行逆向工程?可以说我正在查看上面的快捷方式示例,并且想在没有快捷方式的情况下以 "traditional" 方式进行操作吗?

"shortcut" 的逆向工程是否类似于下面的代码(我的尝试对我来说似乎不正确)......

我的Attempt/Example

class Lamp

  def initialize(color, is_on)
    @color = color
    @is_on = is_on
  end

  def color=(color)
    @color = color
  end

   def is_on=(is_on)
    @is_on = is_on
  end

  def color
    @color
  end

  def is_on
    @is_on
  end

end

我的尝试是right/workable代码吗?当谈到这个 getter/setter 东西时,我似乎在概念上错过了一块。

了解 attr_accesor、attr_reader 和 attr_writer

这些是 Ruby 的 getter 和 setter 的快捷方式。它像 C# 属性一样工作,注入 get_Prop (getter) 和 set_Prop (setter) 方法。

  • attr_accessor:注入prop(getter)和prop=(setter)方法。
  • attr_reader:这是 read-only 属性的快捷方式。注入 prop 方法。 prop值只能在class内部改变,操作实例变量@prop.
  • attr_writer:它是 write-only 属性的快捷方式。注入 prop= 方法。

Ruby 没有名为 get_prop (getter) 和 set_prop (setter) 的方法,相反,它们被称为 prop (getter) 和 prop= (setter).

话虽这么说,你可以推断

class Person
  attr_accessor :name, :age
end

的缩写
class Person
  # getter
  def name
    return @name
  end

  # setter
  def name=(value)
    @name = value
  end
end

您不需要调用 return、Ruby 方法 returns 最后执行的语句。

如果您在 Rails gem 上使用 Ruby,您可以使用 new 构建模型对象并将属性值作为参数传递,就像:

p = Person.new(name: 'Vinicius', age: 18)
p.name
=> 'Vinicius'

这是可能的,因为 Rails 向 ActiveRecord::Base 和 class 注入了类似 initialize 的方法,其中包括 ActiveModel::Model:

def initialize(params)
  params.each do |key, value|
    instance_variable_set("@#{key}", value)
  end
end