当你还在返回超级时覆盖超级时,你如何有条件地执行某些事情?

时间:2013-02-06 23:43:10

标签: ruby subclass superclass

在覆盖超级时如何有条件地执行某些操作,同时仍然返回超级结果?我确信在Ruby中有一种更清晰的写法方式

def my_method
  result = super
  if result.success?
    my_other_method1
    my_other_method2
    if @my_field
      @x = @y
    end
  end

  result
end

我相信可以用块来完成某些事情,但是还没有真正理解它们。任何指针都将非常感激。

2 个答案:

答案 0 :(得分:3)

如果你正在使用ruby 1.9,你可以使用Object#tap方法来清理它。

def my_method
    super.tap do |result|
        if result.success?
            my_other_method1
            my_other_method2
            if @my_field
                @x = @y
            end
        end
    end
end

答案 1 :(得分:1)

你可以这样做:

def my_method
  super || my_other_method
end