Egor Nagornov Egor Nagornov - 1 year ago 83
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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download