我目前正在做一些关于 ruby 编程语言的在线教程,我认为到目前为止我所得到的解释/示例是缺乏的。在直接问这个问题之前,我想给你看两个例子。
第一个例子是:
传统的 Getter/Setter;
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/Setter;
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”方法并将“红色”或“蓝色”传递给我的 setter 中的参数 (ink_color)。然后,如果我想访问或“Get/Getter”我有“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 的东西时,我似乎在概念上错过了一 block 。
最佳答案
理解 attr_accesor、attr_reader 和 attr_writer
这些是 Ruby 的 getter 和 setter 快捷方式。它像 C# 属性一样工作,注入(inject) get_Prop
(getter) 和 set_Prop
(setter) 方法。
attr_accessor
:注入(inject)prop
(getter)和prop=
(setter)方法。attr_reader
:它是只读属性的快捷方式。注入(inject)prop
方法。prop
值只能在类内部更改,操作实例变量@prop
。attr_writer
:它是只写属性的快捷方式。注入(inject)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 方法会返回最后执行的语句。
如果您使用 Ruby on Rails gem,您可以使用 new
构建模型对象并将属性值作为参数传递,就像:
p = Person.new(name: 'Vinicius', age: 18)
p.name
=> 'Vinicius'
这是可能的,因为 Rails 向 ActiveRecord::Base
和包含 ActiveModel::Model
的类注入(inject)了类似这样的initialize
方法:
def initialize(params)
params.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
关于ruby - 我试图理解 ruby 编程语言中的 "Getters"和 "Setters",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48974882/