I have been coding for three or four months (started in Python) and I am just getting into Ruby on account of Rails popularity.
To help build my understanding of the Ruby language, I have been going through the problems on Ruby Monk. The Ruby Primer: Ascent 1.1 - Understanding Inheritance course has the following problem:
Write a method that takes a class and a subclass as arguments and returns a boolean regarding whether or not the subclass is an ancestor of the class.
Here is what I came up with (note: Ruby Monk decided to go with spelling "klass" for "class"):
def is_ancestor?(klass, subclass)
subclass.ancestors.map{ |ancestor| ancestor.to_s }.include? klass.to_s
end
This code passes all tests except for a special one that states doesn't use any other methods to solve the problem (yes, there's a shortcut :))
.
I was really vexed as to how to solve this without using other methods, and so I looked at the proposed solution. Here is what Ruby Monk says that answer should be.
def is_ancestor?(klass, subclass)
current_class = subclass
while !current_class.superclass.nil? && current_class != klass
current_class = current_class.superclass
end
current_class == klass
end
I understand this code. What I don't understand is why this code passes the test requirement of not using methods while my code doesn't. After all, the Ruby Monk proposed answer does use methods (see !current_class.superclass.nil
).
Am I missing something here? Perhaps I don't really understand what a method is. Perhaps my code does work and is only failing because Ruby Monk is performing tests that match code 1:1.
Aucun commentaire:
Enregistrer un commentaire