Adding new methods in Ruby
Classes are always open in Ruby. New methods can be added at any time.
# Create a new class\n class MyClass\n end\n\n # Create an instance\n a = MyClass.new\n\n # Send a message for a non-existent method\n a.f # => NoMethodError: undefined method `f' for #<MyClass:0x1a1810>\n\n # Open the class and add a new method\n class MyClass\n def f(name)\n puts "Hi from #{name}"\n end\n end\n\n # Now the instance will recognize the message\n a.f("a class") # => "hi from a class"
--
-- Jim Weirich jweirich@one.net [link|http://onestepback.org|http://onestepback.org]
---------------------------------------------------------------------
"Beware of bugs in the above code; I have only proved it correct,
not tried it." -- Donald Knuth (in a memo to Peter van Emde Boas)