- Published
- Author
- Syed SibtainSystem Analyst
define_singleton_method dynamically adds a method to a single object instance without modifying the class itself. This is useful when you need custom behaviour for an individual object at runtime.It only modifies the behaviour of a single object in memory at runtime. It does not persist any changes to the database or schema.
Code
user = User.new(name: "Sibtain")
user.define_singleton_method(:greet) do
"Hello, my name is #{name}!"
end
puts user.greet # => "Hello, my name is Sibtain"#CU6U0R822