Ruby:方法别名:子-父类

Ruby:方法别名:子-父类,ruby,class,methods,parent-child,alias,Ruby,Class,Methods,Parent Child,Alias,我有以下资料: class Parent def A return 'A' end def B return 'B' end end class Child < Parent def A super return 'Child.A' end def B super return 'Child.B' end end 它返回我'A',而不是'Child.A'。我在找一个孩子。 我希望语法也能做到以下几点 Cla

我有以下资料:

class Parent
  def A
    return 'A'
  end
  def B
    return 'B'
  end
end

class Child < Parent
  def A
    super
    return 'Child.A'
  end
  def B
    super
    return 'Child.B'
  end
end
它返回我'A',而不是'Child.A'。我在找一个孩子。 我希望语法也能做到以下几点

Class GrandChild < Child
  alias method_of_GrandChild_A A #if Grandchild.A doesn't exist, 
                                 #it will alias Child.A instead.
                                 #Which what alias does basically.
  def A
    method_of_GrandChild_A
  end
end
类孙子
因此,当我这样做时: p孙子 =>儿童A


我对alias函数不太熟悉,有人能告诉我吗?谢谢

我相信您的代码已经如您所期望的那样工作了:

require 'pry'
class Parent
  def A; 'A'; end
  def B; 'B'; end
end

class Child < Parent
  def A; 'Child.A'; end
  def B; 'Child.B'; end
end

class Child < Parent
  alias method_of_child_A A
  def A
    method_of_child_A
  end
end

p Child.new.A #=> "Child.A"
需要“撬动”
班级家长
定义A;'A';结束
定义B;'B';结束
结束
类子<父
定义A;'儿童A′;结束
定义B;'儿童B′;结束
结束
类子<父
子对象的别名方法
定义A
子方法
结束
结束
p Child.new.A#=>“Child.A”

我的编辑是修饰性的,使代码稍微短一些。

如果我想让定义有super呢?你可以把它放在那里,它在示例代码中没有做任何事情,所以我只是把它拉了出来。我不会用一行def格式化生产代码,只是尽量简洁。
Class GrandChild < Child
  alias method_of_GrandChild_A A #if Grandchild.A doesn't exist, 
                                 #it will alias Child.A instead.
                                 #Which what alias does basically.
  def A
    method_of_GrandChild_A
  end
end
require 'pry'
class Parent
  def A; 'A'; end
  def B; 'B'; end
end

class Child < Parent
  def A; 'Child.A'; end
  def B; 'Child.B'; end
end

class Child < Parent
  alias method_of_child_A A
  def A
    method_of_child_A
  end
end

p Child.new.A #=> "Child.A"