用Ruby中的getter覆盖方法

Dan*_*n M 5 ruby inheritance overriding

下面的代码按预期运行,但是使用属性的getter 覆盖方法(请参阅下面的代码中的action_label)是否有任何缺点?请参阅代码中的:action_label

class BaseAction
  def action_label
    raise NotImplementedError
  end

  def run
    puts "Running action: #{action_label}"
    yield        
  end
end

class SimpleAction < BaseAction  

  def initialize(label)    
    @action_label = label
  end

  private
  attr_reader :action_label
end

sa = SimpleAction.new("foo")
sa.run {puts "action!"}
Run Code Online (Sandbox Code Playgroud)

Max*_*Max 2

attr_reader :action_label只是定义一个方法。Ruby 中的“getters”就是这样的方法

def action_label
  @action_label
end
Run Code Online (Sandbox Code Playgroud)

attr_reader是定义此类方法的简写。

在子类中重新定义方法并没有什么问题,这是 OOP 的一大特点。

而且这也不是NotImplementedError的用途。举起别的东西。