从另一个类调用方法。这个怎么运作?

时间:2016-05-05 03:55:54

标签: ruby oop

在另一个类中定义的方法,我不明白方法是如何相互关联的

class Route
 attr_reader :stations #getter method
end

class Train
  attr_accessor :route #getter and setter method

  def show_stations
     route.stations # How it works?
  end
end

route = Route.new
train = Train.new

train.route = route
train.show_stations

1 个答案:

答案 0 :(得分:0)

当方法调用具有显式接收器时,从哪个上下文调用它并不重要。重要的是接收器有这种方法。

方法调用route.stations的上下文无关紧要。重要的是接收方route是否具有方法stations。由于routeRoute个实例,因此它的方法stationsattr_reader :stations定义。