如何通过attr数组的内容查找类实例?

时间:2017-06-27 19:36:39

标签: arrays ruby search

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')

我如何通过@@ all搜索包含特定项目的梳妆台名称,比如帽子? 编辑:实现了我最初输入的代码不正确。糟糕!

1 个答案:

答案 0 :(得分:1)

添加阅读器contents方法,然后调用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"]>]