stardiviner
8/3/2014 - 4:42 AM

location_in_hierarchy.rb

# are below them in the inheritance chain.

# In this problem, the location_in_hierarchy method takes two parameters: object
# and method. You've to find the very first superclass of the object (starting
# with BasicObject) that defines method.

def location_in_hierarchy(object, method)
  puts klass = object.class
  p ancestors = [klass]
  while not (superclass = klass.superclass).nil?
    p ancestors << superclass
    puts klass = superclass
  end
  ancestors.reverse.find do |ancestor|
    p ancestor.instance_methods.include?(method)
  end
end

class Hi
  def say
    puts 'hi'
  end
end

hi = Hi.new

p location_in_hierarchy(hi, :say)
# NOTE: "say" will fail
# p location_in_hierarchy(hi, "say")