4
#!/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?

3
  • 1
    report = reports.select{|r| e.name == 1}.name Commented Sep 16, 2012 at 15:22
  • 1
    you're missing an attr_accessor for description though,. Commented Sep 16, 2012 at 15:22
  • oops, true, my select would raise an horrible error :) -sorry Commented Sep 16, 2012 at 15:29

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I like it, but Wayne's answer is easier and everything is based on the ID, so will be faster and more maintainable.
4

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.

3 Comments

Never thought of using the reports[x] setup. Easy and simple.
In such cases, is it better to remove @id from OReport instance and use reports.key(report) when you need to refer an id, or is it better to leave it as in your answer?
@sawa, If an instance of OReport needs to know its ID for some purpose, then it must retain it. Otherwise, the ID can be kept solely as a hash key, if desired.
0

You can get reports for 2 by the following syntax.

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

it will surely work for you.

1 Comment

What if they're added to the array in a different order?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.