Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 357
WernerCD Avatar asked Dec 09 '22 21:12

WernerCD


1 Answers

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.

like image 142
Andrew Marshall Avatar answered Dec 20 '22 22:12

Andrew Marshall