Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 如何通过attr数组的内容查找类实例?_Arrays_Ruby_Search - Fatal编程技术网

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

Arrays 如何通过attr数组的内容查找类实例?,arrays,ruby,search,Arrays,Ruby,Search,我如何在@@all中搜索包含特定物品(如帽子)的梳妆台的名称? 编辑:意识到我最初输入的代码不正确。哎呀 添加读卡器内容方法,然后调用select 这可以通过查看任何数组的相同方式解决。。也许可以先解决一些不太复杂的问题来理解这个过程:编写代码来查找以下数组中包含数字2的数组:[[1,2,3],[1],[2]]。结果应该是[[1,2,3],[2]]。在解决这个问题的过程中,这里提出并隐藏在非常特定情况下的问题将得到解决:外部数组是'@@all',每个嵌套数组是特定实例的'@contents'。使

我如何在@@all中搜索包含特定物品(如帽子)的梳妆台的名称? 编辑:意识到我最初输入的代码不正确。哎呀

添加读卡器内容方法,然后调用select


这可以通过查看任何数组的相同方式解决。。也许可以先解决一些不太复杂的问题来理解这个过程:编写代码来查找以下数组中包含数字2的数组:[[1,2,3],[1],[2]]。结果应该是[[1,2,3],[2]]。在解决这个问题的过程中,这里提出并隐藏在非常特定情况下的问题将得到解决:外部数组是'@@all',每个嵌套数组是特定实例的'@contents'。使用类实例变量,如@all,可能会给您带来麻烦,所以在做这件事时要小心。我知道如何在嵌套数组中找到特定数组,并且我知道如何根据它们的属性(如本例中的高度或名称)搜索实例。我只是还没有弄清楚如何通过属性化数组的内容来查找类实例。我所能做的最好的事情就是找到并返回特定数组本身,但不引用它所属的实例,这就是问题所在。因此,我可以找到包含“hat”的数组并将数组本身返回给我,但我不知道它们来自哪个梳妆台。梳妆台。所有。每个{d |放置d.contents。选择{c | c.include?'hat'}这是我能想到的最好的梳妆台,但正如我所说,它无法告诉我是哪个梳妆台。它只是找到了帽子。哇,我确实试过了,只是错过了reader方法。德普。谢谢我很困惑为什么它不起作用,也没有意识到我遗漏了一个简单的基本原理。
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')
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"]>]