Ruby, Array, Object - select an 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 can I now search for β€œReports” for 2 so that I can extract a name and description from it?

+4
source share
3 answers

If the primary use for reports is to extract 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" 

Searching for hashes is usually faster than searching in an array, but more importantly, easier.

+4
source

Use find to get an object from the collection with the condition:

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

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

+10
source

You can get reports for 2 with the following syntax.

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

it will surely work for you.

0
source

Source: https://habr.com/ru/post/1434471/


All Articles