Forum: Ruby on Rails One liner please

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
leonleslie (Guest)
on 2005-11-12 13:49
(Received via mailing list)
Hi Railers,

I have the following code which attempts to find missing years in a
list of active records.

  It creates a range of years for which filing documents are required.
  Then deletes all the years for which there are documents
  returning a list of years for which no documents where found.

I am newbie to ruby, rails and blocks. Can someone help me write this
more effectively?

def outstanding_annual_return_years
  outstanding = []
  result = formation_date.strftime("%Y").to_i
  result.upto(Time.now.strftime("%Y").to_i) {|y| outstanding << y}
  filed_documents.each {|d|
    outstanding.delete d.filing_date.strftime("%Y").to_i
  }
  outstanding
end

Thanks
jamis (Guest)
on 2005-11-12 13:49
(Received via mailing list)
On Nov 9, 2005, at 3:13 PM, Leon L. wrote:

> more effectively?
>
> def outstanding_annual_return_years
>   outstanding = []
>   result = formation_date.strftime("%Y").to_i
>   result.upto(Time.now.strftime("%Y").to_i) {|y| outstanding << y}
>   filed_documents.each {|d|
>     outstanding.delete d.filing_date.strftime("%Y").to_i
>   }
>   outstanding
> end

def outstanding_annual_return_years
   (formation_date.year..Time.now.year).to_a -
     filed_documents.map { |f| f.filing_date.year }
end

What this does is take the year from the formation date and the year
from today, and create a range out of them (a..b).

Then, it converts the range to an array (to_a). This gives you an
array of all the years between the two years, inclusive.

Then it creates an array of all years for the filing dates using
Array#map. This basically creates a new array, where each element of
the array is replaced by the result of the associated block.

So, now we have two arrays--one with all the years, and one with the
years for which there are documents.

Finally, we just take the difference between the two arrays, which
gives you all elements in the first array that do not exist in the
second array.

Hope that makes sense. :)

- Jamis
leonleslie (Guest)
on 2005-11-12 13:49
(Received via mailing list)
Hi Jamis,

This was fast.. . Makes perfect sense,  And works like the breeze :)

Thank you....


On 11/9/05, Jamis B. <removed_email_address@domain.invalid> wrote:
> >
> >   outstanding
> Then, it converts the range to an array (to_a). This gives you an
> gives you all elements in the first array that do not exist in the
>
--
First they laugh at you, then they ignore you, then they fight you.
Then you win.
-- Mahatma Karamchand Gandhi
This topic is locked and can not be replied to.