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的超类中调用另一个方法 甲级 定义a 放入“a” 结束 结束 B类_Ruby - Fatal编程技术网

在ruby的超类中调用另一个方法 甲级 定义a 放入“a” 结束 结束 B类

在ruby的超类中调用另一个方法 甲级 定义a 放入“a” 结束 结束 B类,ruby,Ruby,没有很好的方法可以做到这一点,但是你可以使用A.instance\u方法(:A).bind(self).call,它可以工作,但是很难看 您甚至可以在Object中定义自己的方法,使其与java中的super类似: class A def a puts 'in #a' end end class B < A def a b() end def b # here i want to call A#a. end end 类超氧化物 def初始化

没有很好的方法可以做到这一点,但是你可以使用
A.instance\u方法(:A).bind(self).call
,它可以工作,但是很难看

您甚至可以在Object中定义自己的方法,使其与java中的super类似:

class A def a puts 'in #a' end end class B < A def a b() end def b # here i want to call A#a. end end
类超氧化物
def初始化(obj)
@obj=obj
结束
def方法_缺失(meth、*args和blk)
@obj.class.superclass.instance_方法(meth).bind(@obj.call(*args,&blk)
结束
结束
类对象
私有的
def sup
SuperProxy.新(自)
结束
结束
甲级
定义a
将“放在A#A中”
结束
结束
B类<代码>B类
如果您不需要明确地从B#B调用A#A,而是需要从B#A调用A#A,这实际上就是通过B#B所做的(除非您的示例不够完整,无法说明为什么要从B#B调用,否则您可以从B#a内部调用super,就像有时在初始化方法中所做的那样。我知道这是很明显的,我只是想向任何Ruby新手澄清,您不必使用别名(具体来说,这有时被称为“环绕别名”)在任何情况下

class B < A

  alias :super_a :a

  def a
    b()
  end
  def b
    super_a()
  end
end  
A类
定义a
#为一个人做事
结束
结束
B类
@klochner我不同意,这个解决方案正是我所需要的…原因:我想通用地调用另一个方法的super方法,但不需要对我想调用的每个方法都进行别名,所以调用super的通用方法非常有用,一次定义很复杂,多次调用很简单。这就是比反之更好。若要给类方法加别名,请参阅自编写此答案以来,
别名
是否有可能被重命名为?@JaredBeck它确实被重命名了。所以现在它应该是:别名方法:超级a:a这是怎么回事?为什么不将
:超级a
化名为
B.a
,而将其化名为
a.a
?@MarkoAvlijaš在您创建别名时,
B.a
尚未定义…如果您将
别名
放在
定义a
下面,则情况并非如此
class B < A

  alias :super_a :a

  def a
    b()
  end
  def b
    super_a()
  end
end  
class A
  def a
    # do stuff for A
  end
end

class B < A
  def a
    # do some stuff specific to B
    super
    # or use super() if you don't want super to pass on any args that method a might have had
    # super/super() can also be called first
    # it should be noted that some design patterns call for avoiding this construct
    # as it creates a tight coupling between the classes.  If you control both
    # classes, it's not as big a deal, but if the superclass is outside your control
    # it could change, w/o you knowing.  This is pretty much composition vs inheritance
  end
end