Note that there are some explanatory texts on larger screens.

plurals
  1. POSafely & efficiently sort on a possibly-missing attribute?
    primarykey
    data
    text
    <p>Here's what I'm doing:</p> <pre><code>offers = v.offers.sort { |a,b| a.expires &lt;=&gt; b.expires } </code></pre> <p>This data is loaded via ActiveResource (so each set of instance attributes is defined by the data it contains). However, a recent change in the incoming data has made the "expires" attribute optional. Is there a class definition change that will cause the sort method to go grab a default value if the attribute is missing from an instance?</p> <p>edit: @Nikita</p> <p>It looks like it won't be that simple:</p> <pre><code>o.expires == nil? NoMethodError: undefined method `expires' for #&lt;Offer:0x00000100d3faa8&gt; o.expires? =&gt; nil </code></pre> <p>so I tried:</p> <pre><code>offers.sort{|a,b| if a.expires? b.expires? ? 0 : -1 else b.expires? ? 1 : a.expires &lt;=&gt; b.expires end } NoMethodError: undefined method `expires' for #&lt;Offer:0x00000100d3faa8&gt; </code></pre> <p>I was hoping to be able to update the class definition with something like:</p> <pre><code>expires ||= "" </code></pre> <p>... but I don't know if that's possible. I don't really follow how the sorting blocks work yet, though. I know I could just loop through the offers and assign the value, but it seems grossly inefficient.</p> <p><strong>update</strong></p> <pre><code>offers.sort{|a,b| if defined? a.expires == nil (defined? b.expires == nil) ? 0 : -1 else (defined? b.expires == nil) ? 1 : a.expires &lt;=&gt; b.expires end } ArgumentError: comparison of Offer with Offer failed from (irb):70:in `sort' from (irb):70 from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta4/lib/rails/commands/console.rb:47:in `start' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta4/lib/rails/commands/console.rb:8:in `start' from /usr/local/lib/ruby/gems/1.9.1/gems/railties-3.0.0.beta4/lib/rails/commands.rb:23:in `&lt;top (required)&gt;' from script/rails:6:in `require' from script/rails:6:in `&lt;main&gt;' </code></pre> <p>Hooray for verbosity ;p</p>
    singulars
    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. 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