Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>A few observations before I post an example of how to rework that.</p> <ul> <li>Giving a class a plural name can lead to a lot of semantic issues when declaring new objects, as in this case you'd call Items.new, implying you're creating several items when in fact actually making one. Use the singular form for individual entities.</li> <li>Be careful when calling arbitrary methods, as you'll throw an exception on any misses. Either check you can call them first, or rescue from the inevitable disaster where applicable.</li> </ul> <p>One way to approach your problem is to make a custom collection class specifically for Item objects where it can give you the information you need on names and such. For example:</p> <pre><code>class Item attr_accessor :item_id, :name, :description, :rating def initialize(options = { }) options.each do |k,v| method = :"#{k}=" # Check that the method call is valid before making it if (respond_to?(method)) self.send(method, v) else # If not, produce a meaningful error raise "Unknown attribute #{k}" end end end end class ItemsCollection &lt; Array # This collection does everything an Array does, plus # you can add utility methods like names. def names collect do |i| i.name end end end # Example # Create a custom collection items = ItemsCollection.new # Build a few basic examples [ { :item_id =&gt; 1, :name =&gt; 'Fastball', :description =&gt; 'Faster than a slowball', :rating =&gt; 2 }, { :item_id =&gt; 2, :name =&gt; 'Jack of Nines', :description =&gt; 'Hypothetical playing card', :rating =&gt; 3 }, { :item_id =&gt; 3, :name =&gt; 'Ruby Book', :description =&gt; 'A book made entirely of precious gems', :rating =&gt; 1 } ].each do |example| items &lt;&lt; Item.new(example) end puts items.names.join(', ') # =&gt; Fastball, Jack of Nines, Ruby Book </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload