In Ruby the first instance of class defines the Class and the second modifies it. When you start with Ruby that sounds like a problem, but in fact is very powerful as it allows you to extend classes easily.
Here is an example that demonstrates what is happening:
Code:
class MultiClassTest
def initialize
@multi_class = MultiClass.new
puts "**_Starting_new_test_**"
test_methods_exist
test_method_one
puts "\n"
end
def test_methods_exist
test_method_exists('one')
test_method_exists('two')
end
def test_method_one
puts "Method one returns '#{@multi_class.one}'"
end
def test_method_exists(method_name)
if @multi_class.methods.include?(method_name)
puts "Method #{method_name} found"
else
puts "Method #{method_name} not found"
end
end
end
class MultiClass
def one
"one"
end
end
MultiClassTest.new
class MultiClass
def two
"two"
end
end
MultiClassTest.new
class MultiClass
def one
"cheese"
end
end
MultiClassTest.new
This uses two classes. MultiClass is the class we are experimenting with, and MultiClassTest lets us easily run the same tests repeatedly. If you run the code you should get this output:
Code:
**_Starting_new_test_**
Method one found
Method two not found
Method one returns 'one'
**_Starting_new_test_**
Method one found
Method two found
Method one returns 'one'
**_Starting_new_test_**
Method one found
Method two found
Method one returns 'cheese'
As you can see, when MultiClassTest.new is first called only the method 'one' exists. The second time the second method 'two' has been added to the class. The third time the method 'one' has been overwritten with a new definition.
This also demonstrates one use of the 'methods' method which returns an array of all the methods exisiting for an object. RDoc can give you more information and is used to generate the core API information.
Bookmarks