Download this source
# This is *very* cool. In Ruby, we can modify classes at any time.
class MyNewClass
def get_number
5
end
end
mnc = MyNewClass.new
puts mnc.get_number
# Here, this would fail
# print mnc.extra(), "\n"
class MyNewClass
# Call the pre-existing method
def extra
get_number + 8
end
# Classes can of course be nested
class MyNestedClass
def method_one
"nested class"
end
# This method will fail - nesting classes affects
# namespace, but it doesn't mean that any instance
# of the outer class is required by the inner,
# or that instance methods will be available from
# it.
def call_extra
extra
end
end
end
# Now, however, the new method is defined. Notice that we didn't create
# a new instance - the change on the class affects existing ones too :)
puts mnc.extra
# We can use our nested class with qualified namespace
mnew = MyNewClass::MyNestedClass.new
puts mnew.method_one
# but this would fail, as mentioned above.
#puts mnew.call_extra
# Now check this out - we can make a 'Singleton' method, which applies only
# to an individual instance
foo = MyNewClass.new
def foo.new_method(a)
puts a
end
# now this works
foo.new_method("Rosco")
# but this would fail at runtime
# mnc.new_method("Rosco")
# A 'singleton class' is a related thing - in fact, the singleton method
# above is defined on our 'singleton class'. There is some debate over
# the term 'singleton' in this context - others you may see are are:
#
# metaclass, eigenclass, ad-hoc (more for methods), etc.
#
# but they're all referring to:
class << foo
def another_new_method(b)
# Call another singleton method
new_method(b)
end
end
# So that now, both are there.
foo.another_new_method("flexibility")
Running this outputs:
5
13
nested class
Rosco
flexibility

