【问题标题】:Ruby, Array, Object - Select ObjectRuby、数组、对象 - 选择对象
【发布时间】:2012-09-09 00:16:09
【问题描述】:
#!/usr/local/bin/ruby
class OReport
   attr_accessor :id, :name
   def initialize(id, name, desc)
      @id       = id
      @name     = name
      @desc     = desc
   end
end

reports = Array.new
reports << OReport.new(1, 'One', 'One Desc')
reports << OReport.new(2, 'Two', 'Two Desc')
reports << OReport.new(3, 'Three', 'Three Desc')

我现在如何在“报告”中搜索 2,以便从中提取名称和描述?

【问题讨论】:

  • 报告=reports.select{|r| e.name == 1}.name
  • 您缺少用于描述的 attr_accessor。
  • 哎呀,真的,我的选择会引发一个可怕的错误:) - 对不起

标签: ruby arrays search object


【解决方案1】:

使用find从给定条件的集合中获取对象:

reports.find { |report| report.id == 2 }
#=> => #<OReport:0x007fa32c9e85c8 @desc="Two Desc", @id=2, @name="Two">

如果您希望多个对象满足条件,并且希望所有对象而不是第一个匹配的对象,请使用select

【讨论】:

  • 我喜欢它,但是韦恩的回答更简单,一切都基于ID,所以会更快,更易于维护。
【解决方案2】:

您可以通过以下语法获取 2 的报告。

reports[1].name
reports[1].id

它肯定对你有用。

【讨论】:

  • 如果它们以不同的顺序添加到数组中怎么办?
【解决方案3】:

如果reports 的主要用途是通过 id 检索,则考虑使用散列代替:

reports = {}
reports[1] = OReport.new(1, 'One', 'One Desc')
reports[2] = OReport.new(2, 'Two', 'Two Desc')
reports[3] = OReport.new(3, 'Three', 'Three Desc')

p reports[2].name    # => "Two"

哈希查找通常比数组查找更快,但更重要的是,它更简单。

【讨论】:

  • 从未想过使用报告[x] 设置。简单易行。
  • 在这种情况下,最好从 OReport 实例中删除 @id 并在需要引用 id 时使用 reports.key(report),还是将其保留在您的答案中更好?
  • @sawa,如果 OReport 实例出于某种目的需要知道其 ID,则它必须保留它。否则,如果需要,可以将 ID 单独保留为哈希键。
猜你喜欢
  • 2013-12-16
  • 1970-01-01
  • 1970-01-01
  • 2016-11-02
  • 2013-11-25
  • 2020-01-27
  • 1970-01-01
  • 2019-01-18
  • 1970-01-01
相关资源
最近更新 更多