#!/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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With