Tristin
Tristin

Reputation: 69

How to find class instances by contents of attr array?

class Dresser
  @@all = []
  attr_accessor :name, :height, :length, :width, :contents
  def initialize (name, height,length, width)
    @name = name
    @height = height
    @length = length
    @width = width
    @contents = []
    @@all << self
  end

  def Dresser.all
    @@all
  end

  def add_content(content)
    @contents << content
  end
end

a = Dresser.new('a', 4, 6, 8)
a.add_content('sock')
a.add_content('hat')
b = Dresser.new('b', 3, 6, 9)
b.add_content('bra')
c = Dresser.new('c', 4, 7, 6)
c.add_content('hat')

How would I go about searching through @@all for the name of dressers that contain a specific item, say a hat? Edit: Realized the code I initially entered was incorrect. Whoops!

Upvotes: 0

Views: 47

Answers (1)

Sagar Pandya
Sagar Pandya

Reputation: 9497

Add a reader contents method then call select.

class Dresser

#rest of your code

  def contents
    @contents
  end
end

#Assuming your instance additions
Dresser.all.select {|d| d.contents.include? 'hat'}
=>
[#<Dresser:0x000000020b0890 @name="a", @height=4, @length=6, @width=8, @contents=["sock", "hat"]>,
 #<Dresser:0x000000020b0728 @name="c", @height=4, @length=7, @width=6, @contents=["hat"]>]

Upvotes: 1

Related Questions