0

How would one go about keeping track of a classes objects by pushing the new instances to an Array, and to allow this array to be edited/popped by an object of another class.

For example;

  • The object 'airplane' (Plane class) is created, and pushed to an Array called 'in-flight'.

  • The object 'airport' (Airport class) asks it to land and pops from the array.

Is there a way to do so, with and/or without the use of class variables?

1
  • Use a factory method to create airplane objects, instead of creating them directly with .new. This factory method, beside creation of objects, can also register them in some array or whatever Commented Sep 6, 2015 at 19:23

1 Answer 1

1

You could do this by overriding the initialize method of the Airplane class. Something like this:

class Airplane
  class << self
    attr_accessor :in_flight
  end
  self.in_flight ||= []

  def initialize(*)
    self.class.in_flight << self
    super
  end

  def land!
    self.class.in_flight.delete(self)
  end
end

then, from anywhere else in your codebase, do something like this:

# We'll just pick a random airplane from the list of those in
# flight, but presumably you would have some sort of logic around
# it (already have an Airplane instance somehow, select one from
# the array according to some criteria, etc).
airplane = Airplane.in_flight.sample
airplane.land!

Not sure that this is the greatest application design in the world, but it will certainly do if your needs are simple.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.