環境
- Ruby 2.6
やりたいこと
方法1 class_eval
class Cat def self.hello "nyaa" end end Cat.class_eval do def self.hello "bowwow" end end puts Cat.hello
方法2 define_singleton_method
class Cat def self.hello "nyaa" end end orig = Cat.method(:hello) # 元のメソッドを呼びたい時は必要 Cat.define_singleton_method(:hello) do "#{orig.call} > bowwow" end puts Cat.hello
方法3 Module#prepend
class Cat def self.hello "nyaa" end end Cat.singleton_class.prepend Module.new { def hello "#{super} > bowwow" end } puts Cat.hello