Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.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 在此方法调用方的上下文中调用super_Ruby - Fatal编程技术网

Ruby 在此方法调用方的上下文中调用super

Ruby 在此方法调用方的上下文中调用super,ruby,Ruby,我有几种方法,它们具有相似的条件逻辑,我认为干燥它们是合理的 class A def parent1(val) puts "parent1 A #{val}" end def parent2(val) puts "parent2 A #{val}" end end class B < A def parent1(val) if val puts "foo" else super end end

我有几种方法,它们具有相似的条件逻辑,我认为干燥它们是合理的

class A
  def parent1(val)
    puts "parent1 A #{val}"
  end

  def parent2(val)
    puts "parent2 A #{val}"
  end
end

class B < A
  def parent1(val)
    if val
      puts "foo"
    else
      super
    end
  end

  def parent2(val)
    if val
      puts "bar"
    else
      super
    end
  end
end
编辑:这很有效,但看起来很疯狂

def puts_or_super(val, text)
  if val
    puts text
  else
    self.class.superclass.instance_method(caller[0][/`.*'/][1..-2].to_sym).bind(self).call
  end
end

有更好的解决方案吗?

假设您的定义在类
A
中,并且相关的超级方法在类
B
中定义,以便
A
继承自
B

我认为你应该走另一条路。使
B
a模块,并将
B
前置到
a
。然后,具有
“foo”
“bar”
等的定义将不是超级方法,条件将在前置模块中

module B
  def parent1(val)
    return super if val
    ... # your original logic in super class
  end
  def parent2(val)
    return super if val
    ... # your original logic in super class
  end
end

class A
  prepend B
  def parent1(_); puts "foo" end
  def parent2(_); puts "bar" end
end

super
用于类继承。您使用两种不同的方法。您能否扩展您的示例以显示您希望在哪些类中使用您的示例?你想叫什么?我只是想简单点。
parent1
parent2
都属于继承自另一个类的类。也许我提供了一个不好的示例,所以我决定不回答我的问题,而是简化示例。对不起,那不是我需要的。基本上,我想干燥
parent1
parent2
方法,特别是
super
调用部分。
module B
  def parent1(val)
    return super if val
    ... # your original logic in super class
  end
  def parent2(val)
    return super if val
    ... # your original logic in super class
  end
end

class A
  prepend B
  def parent1(_); puts "foo" end
  def parent2(_); puts "bar" end
end