define_singleton_method

define_singleton_method(symbol, method) â new_method
define_singleton_method(symbol) { block } â proc
Instance Public methods

Defines a singleton method in the receiver. The method parameter can be a Proc, a Method or an UnboundMethod object. If a block is specified, it is used as the method body.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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!"
doc_ruby_on_rails
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.