Egor Nagornov Egor Nagornov - 6 months ago 17
Ruby Question

Call methods from another class. How it works?

The method defined in a different class and I don't understand how methods are associated with each other

class Route
attr_reader :stations #getter method

class Train
attr_accessor :route #getter and setter method

def show_stations
route.stations # How it works?

route =
train =

train.route = route


When a method call has an explicit receiver, it doesn't matter in what context you call it from. All that matters is that the receiver has that method.

The context of method call route.stations does not matter. All that matters is whether the receiver route has the method stations. Since route is a Route instance, it does have the method stations, as defined by attr_reader :stations.