動かざることバグの如し

近づきたいよ 君の理想に

Rubyでクラスメソッドを上書きする方法

環境

やりたいこと

方法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