Ruby 2.4.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Objectクラス > define_singleton_method
define_singleton_method(symbol, method) -> Symbol
[permalink][rdoc]define_singleton_method(symbol) { ... } -> Symbol
self に特異メソッド name を定義します。
class A
class << self
def class_name
to_s
end
end
end
A.define_singleton_method(:who_am_i) do
"I am: #{class_name}"
end
A.who_am_i # ==> "I am: A"
guy = "Bob"
guy.define_singleton_method(:hello) { "#{self}: Hello there!" }
guy.hello #=> "Bob: Hello there!"