WernerCD
WernerCD

Reputation: 2157

Ruby, Array, Object - Select Object

#!/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')

How do I now search "Reports" for 2, so that I can extract name and description from it?

Upvotes: 4

Views: 5544

Answers (3)

Wayne Conrad
Wayne Conrad

Reputation: 107989

If the primary use for reports is to retrieve by id, then consider using a hash instead:

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"

Hash lookup is usually faster than array lookup, but more important, it's simpler.

Upvotes: 4

Ramiz Raja
Ramiz Raja

Reputation: 6030

You can get reports for 2 by the following syntax.

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

it will surely work for you.

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96934

Use find to get an object from a collection given a condition:

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

If you expect more than one object to meet the condition, and want all of them instead of the first matching one, use select.

Upvotes: 10

Related Questions