代码之家  ›  专栏  ›  技术社区  ›  Ghoyos

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

  •  1
  • Ghoyos  · 技术社区  · 8 年前

    我目前正在做一些关于ruby编程语言的在线教程,我认为目前为止我所得到的解释/示例还不够。在直接提问之前,我想向大家展示两个例子。

    第一个例子是:

    传统的接受者/接受者;

    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
    

    第二个例子是:

    快捷键获取器/设置器;

    class Lamp
      attr_accessor :color, :is_on
    
      def initialize(color, is_on)
        @color, @is_on = color, false
      end
    end
    

    对于第一个例子,我认为这很简单。在我的整个Lamp类中,我正在“初始化”一个名为“@ink\u color”的可访问变量。如果我想将“@ink\u color”设置为红色或蓝色,我只需调用我的“Setter”方法,并将“red”或“blue”传递给Setter中的参数(ink\u color)。然后,如果我想访问或“获取/获取”我的“设置/设置”颜色,我会调用我的Getter方法并请求“ink\u color”。

    第二个例子对我来说也很有意义;ruby没有键入getter和setter方法是什么样子,而是提供了一个“快捷方式”,基本上可以运行代码来为您构建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
    

    我的尝试是否正确/可行?在这件事上,我似乎在概念上遗漏了一件事。

    1 回复  |  直到 8 年前
        1
  •  3
  •   vinibrsl    8 年前

    了解attr\u accesor、attr\u reader和attr\u writer

    这些是Ruby的getters和setters快捷方式。它的工作方式类似于C#属性,它注入 get_Prop (getter)和 set_Prop (setter)方法。

    • attr_accessor :注入 prop (getter)和 prop= (setter)方法。
    • attr_reader :这是只读属性的快捷方式。注入 道具 方法这个 道具 值只能在类内部更改,操作实例变量 @prop .
    • attr_writer :这是只写属性的快捷方式。注入 道具= 方法

    Ruby没有调用的方法 get_prop (getter)和 set_prop (塞特),取而代之的是 道具 (getter)和 道具= (设定器)。

    话虽如此,你可以推断

    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方法返回最后执行的语句。

    如果您使用的是Ruby on Rails gem,那么可以使用 new 并将属性值作为参数传递,就像:

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

    这是可能的,因为Rails注入了这样的内容 initialize 方法到 ActiveRecord::Base 以及包括 ActiveModel::Model :

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