Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
理解Ruby setter_Ruby - Fatal编程技术网

理解Ruby setter

理解Ruby setter,ruby,Ruby,如果我创建这样的类: class Player def initialize(position, name) @position = position @name = name end end 这不是将名称设置为实例变量吗?如果是这样,我为什么要写这样的二传手呢 class Player def initialize(position, name) @position = position @name = name end def

如果我创建这样的类:

class Player

  def initialize(position, name)
    @position = position
    @name = name
  end

end
这不是将名称设置为实例变量吗?如果是这样,我为什么要写这样的二传手呢

 class Player

  def initialize(position, name)
    @position = position
    @name = name
  end

  def name=(name)
    @name = name
  end

 end

基本上,什么时候需要在类中编写getter?

getter/setter(也称为“访问器”)可以在类之外访问,而实例变量则不能。如果希望能够从类外部读取或更改
@name
,则需要为其定义访问器


此外,访问器方法允许您执行一定量的健全性检查或更改传入/传出值,并以其他方式保护对象的内部状态。

初始化
在初始化新对象期间设置属性

keeper = Player.new('goalkeeper','Shilton').
如果要在初始化后更新
keeper
的属性,该怎么办?您需要使用普通的setter方法:

def name=(name)
  @name = name
end
像这样:

keeper.name = 'Banks'
如果没有为播放器实例定义setter方法,那么就不能这样做。对于getter方法也是如此。还请注意,您可以使用以下类似的方法重构代码:


getter和setters的工作是为您提供一个快速的实例变量读写实现,这些变量是您在构造函数中定义的:

class Player
  attr_accessor :name, :position
  def initialize(position, name)
    @position = position
    @name = name
  end
end
您还可以专门为这些变量使用
attr\u reader
(用于getter)和
attr\u writer
(用于setter)

上面的代码:
attr\u accessor:name、:position
播放器
类实例提供了
名称
位置
名称=
位置=
方法

但是,它们不会为getter/setter提供验证或自定义逻辑

例如:您可能希望显示玩家的全名,或者不希望您的代码接受0或负数,在这种情况下,您必须自己编写getter和setter:

class Player
  def initialize(first_name, last_name, position)
    @first_name = first_name
    @last_name = last_name
    @position = position
  end

  # validation for updating position using setter of position
  def position=(new_position)
    raise "invalid position: #{new_position}" if new_position <= 0
    @position = new_position
  end

  # customized getter for name method
  def name
    "#{@first_name} #{@last_name}"
  end
end
职业玩家
def初始化(名字、姓氏、位置)
@first_name=first_name
@姓氏=姓氏
@位置=位置
结束
#使用位置设置器更新位置的验证
def位置=(新位置)
提出“无效位置:#{new_position}”如果new_position你的例子都是关于setter的,但是你的“基本上”总结是关于getter的。这是打字错误还是故意的?
class Player
  def initialize(first_name, last_name, position)
    @first_name = first_name
    @last_name = last_name
    @position = position
  end

  # validation for updating position using setter of position
  def position=(new_position)
    raise "invalid position: #{new_position}" if new_position <= 0
    @position = new_position
  end

  # customized getter for name method
  def name
    "#{@first_name} #{@last_name}"
  end
end