0
votes
class Airport
    
  attr_reader :plane
    
  CAPACITY = 20  

  def initialize
    @plane = []
    @capacity = CAPACITY
  end

  #can land a plane
  def land(plane)
    fail 'plane is full' if  @plane.count >= @capacity
    @plane << plane
  end
        
  def take_off
    fail 'weather is stormy' if @weather
        
    @plane
  end
   
  def weather
    @weather = weather   
  end
end

class Weather
  def stormy?
    [true, false].sample
  end
end

I am new to Ruby. I am a little confused in how to use the method of the Weather class in my Airport class.

I want the take_off method in my Airport class to fail when the weather is reported to be stormy. I am unsure where to begin in understanding object interactions. Any help would be greatly appreciated, thank you

1

1 Answers

0
votes

If you want to fail if weather is stormy, you have to call its stormy? method:

def take_off
  fail 'weather is stormy' if @weather.stormy?

  # do something
end

But in order to get the above working, weather needs to be an instance of Weather. I would simply pass it to the constructor. In addition, I would make it a settable attribute, so you can easily update it:

class Airport
  attr_accessor :weather
  attr_reader :plane

  CAPACITY = 20

  def initialize(weather)
    @weather = weather
    @plane = []
    @capacity = CAPACITY
  end

  # ... 
end

I would also make the weather a little more deterministic, e.g. by having a wind force attribute:

class Weather
  attr_reader :wind_force

  def initialize(wind_force)
    @wind_force = wind_force
  end

  def stormy?
    wind_force >= 10
  end
end

Usage:

weather = Weather.new(3)

airport = Airport.new(weather)

airport.take_off # no exception

airport.weather = Weather.new(12)

airport.take_off # RuntimeError: weather is stormy