【问题标题】:Overwrite an instance attribute conditionally有条件地覆盖实例属性
【发布时间】:2015-09-21 07:38:22
【问题描述】:

我有一个类,我正在尝试根据创建输入来确定输出。

class MyCommand
  attr_accessor :command

  def initialize(command = nil)
    @command = command
  end

  # @return Boolean
  def global?
    @command.start_with?('--global')
  end
end

这样可以正常工作:

foo = MyCommand.new('hello')
foo.command #=> "hello"
foo.global? #=> false

但是,当我通过我的条件时,我得到了一些好的,一些不太好的结果:

bar = MyCommand.new('--global world')
bar.global? #=> true
bar.command #=> "--global world"

command包含我的情况。

我尝试创建另一种方法来从任何具有它的命令中分出--global,但结果略有不同:

bar.command = 'world'
bar.command #=> "world"
bar.global? #=> false

但这会改变bar 的当前状态。

我怎样才能让这个类和方法表现得如此才能使global? 标志即使在命令更改后仍然存在?

更好的是,我是否可以仅在 global? 方法中实现所有更改 - 从而最大限度地减少我对整个类更改的影响?

【问题讨论】:

  • 您希望@command 成为--global world 但在您调用barr.command 时返回world 还是您真的希望@command 成为world 当输入为--global world 时?
  • @Joseph 我想我希望bar.command 返回world,但让bar.global? 返回true

标签: ruby class instance instance-variables


【解决方案1】:

initialize 期间,您可以在设置@command 时去掉--global,您可以将@global 分配为true 或false,然后编辑@global? 以返回值:

class MyCommand
  attr_accessor :command

  def initialize(command = '')
    @command = command.gsub('--global ','')
    @global = command.start_with?('--global') ? true : false
  end

  # @return Boolean
  def global?
    @global
  end
end

请注意,gsub 将删除 '--global ',无论它是在 command 的开头、中间还是结尾,并且假设它后面总是有一个尾随空格,所以如果你不确定您的输入,您需要更强大的东西来处理command

附:刚刚意识到如果commandnil 这将不起作用,因此将默认值更改为空字符串。如果你真的需要它是nil,则需要进行一些额外的检查(但不幸的是我现在必须注销)。

【讨论】:

  • 谢谢!我最终更多地使用了这种方法,将全局状态传递给initialize 并稍后采取行动。
猜你喜欢
  • 2014-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多