Graham Slick Graham Slick - 1 month ago 5
Ruby Question

Find object by attribute

I have a ruby class like this:

class Table
def initialize(name)
@name = name
@columns = {}
end
end


I'm creating different objects:

table_1 = Table.new("First")
table_2 = Table.new("Second")
table_3 = Table.new("Third")


How can I find among the objects of the
Table
class the object having "Second" as
name
attribute ?

Answer

You can keep a reference to an array of instances in the class.

class Table
  @instances = []
  class << self
    attr_accessor :instances
  end

  def initialize(name)
    @name = name
    @columns = {}
    self.class.instances << self
  end
end

Then you can get all the instances by

Table.instances

This, however, will prevent all the Table objects being garbage collected, so it is only feasible if you have only a small amount of Tables and that amount never grows, otherwise you'll have a memory leak.

Comments