Łukasz Korol Łukasz Korol - 1 year ago 46
Ruby Question

Getting value from array and count difference between dates

I have a problem with counting days between end_at and start_at located in object @nearest_vacation.
Structure of object @nearest_vacation:

[#<Vacation id: 11, start_at: "2016-04-30", end_at: "2016-05-02", free: false, reason: "Rocznica", person_id: 1>]

When I try
@nearest_vacation.map{|x| x.end_at}
it returns:
[Mon, 02 May 2016]

This format of date doesn't allow me to do like that:
(end_at - start_at).to_i
. How to properly get values end_at and start_at to calculate difference between dates?

Answer Source

Your problem is that you have an array of Vacations.

If you truly need an array, no problem.

# notice the pluralised variable name
@nearest_vacations.map{|nv| (nv.end_at - nv.start_at)}

The above will return you an array with the differences in dates.

What I suspect is going on here is that you have arrays and instances confused. Which is why you have had to use .map to get the end_at value from your array of vacations.

I think the real question here is why your nearest_vacation is an array. The name of the variable and the fact its not pluralised tells me that you don't want an array, but just one instance. Find where your nearest_vacation variable is being set to an array, fix that, then your code should work.