我试图用ruby编程语言理解“Getters”和“Setters”

时间:2018-02-25 15:00:08

标签: ruby setter getter

我目前正在做一些关于ruby编程语言的在线教程,我认为到目前为止我给出的解释/示例是缺乏的。我有两个例子,我想在直接提问之前告诉你。

第一个例子是:

传统的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

好的,所以对于第一个例子,我认为它很直接。我在整个Lamp类中“初始化”一个名为“@ink_color”的可访问变量。如果我想将“@ink_color”设置为红色或蓝色,我只需调用我的“Setter”方法并将“red”或“blue”传递给我的setter中的参数(ink_color)。然后,如果我想访问或“获取/获取”我有'Set / setter'的颜色,我会调用我的getter方法并要求'ink_color'。

第二个例子对我也有意义;而不是键入getter和setter方法的样子,ruby提供了一个“快捷方式”,它基本上运行代码来为你构建getter和setter。

但接下来的问题是:如何对'快捷'版本进行逆向工程?让我说我正在看我上面的快捷方式示例,并希望在没有捷径的情况下以“传统”方式进行操作?

“快捷方式”的逆向工程看起来像下面的代码(我的尝试对我来说似乎不对)....

我的尝试/示例

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

我的尝试是正确/可行的代码吗?当涉及到这个getter / setter的东西时,它似乎在概念上错过了一块。

0 个答案:

没有答案