ruby 如何为所有子类重新定义超类中的方法?

klsxnrf1  于 2023-08-04  发布在  Ruby
关注(0)|答案(1)|浏览(133)

假设我有这样的类:

class One
  def my_method
    puts 1
  end
end

class Two < One
end

class Three < One
end

字符串
然后我想在一个地方重新定义my_method,使它适用于所有三个类。这是可能的,无论是monkeypatching或其他一些方法?

ej83mcc0

ej83mcc01#

Monkeypatching应该可以工作:

class A
  def hello
    "Hello"
  end
end

class B < A; end

class C < A; end

c = C.new

c.hello # > "Hello"

class A
  def hello # Monkeypatching A to change `hello`.
    "Goodbye"
  end
end

# Hello returns a new value, even though it's an instance of C
c.hello # > "Goodbye"

字符串

相关问题