class Car
attr_reader :doors, :color
def initialize(doors, color)
@doors = doors
@color = color
end
end
class Motorcycle
attr_reader :cc, :color
def initialize(cc)
@cc = cc
@color = obtain_color
end
def obtain_color
'orange' if my_car.color == 'green'
'blue'
end
end
class Vehicles
attr_reader :my_car, :my_motorcycle
def initialize
@my_car = Car.new(4, 'green')
@my_motorcycle = Motorcycle.new(950)
end
def display_colors
puts "my_car color: #{my_car.color}"
puts "my_motorcycle color: #{my_motorcycle.color}"
end
end
my_vehicles = Vehicles.new
my_vehicles.display_colors
Not surprisingly produces the following error:
in 'obtain_color': undefined local variable or method 'my_car' for #<Motorcycle:0x007fc1820690a0 @cc=950> (NameError)
To fix this, I passed in the my_car object like this:
class Car
attr_reader :doors, :color
def initialize(doors, color)
@doors = doors
@color = color
end
end
class Motorcycle
attr_reader :cc, :color
def initialize(cc, my_car)
@cc = cc
@color = obtain_color(my_car)
end
def obtain_color(my_car)
'orange' if my_car.color == 'green'
'blue'
end
end
class Vehicles
attr_reader :my_car, :my_motorcycle
def initialize
@my_car = Car.new(4, 'green')
@my_motorcycle = Motorcycle.new(950, my_car)
end
def display_colors
puts "my_car color: #{my_car.color}"
puts "my_motorcycle color: #{my_motorcycle.color}"
end
end
my_vehicles = Vehicles.new
my_vehicles.display_colors
Question: Is there a way to call my_car.color from within the initialization of Motorcycle without having to pass in the my_car object?