luke <lduncalfe / eml.nope> wrote:
> hi,
>
> i'm having some difficulty in writing a method that takes a number of
> seconds, and returns the equivalent in hours, days, or weeks
> depending on which time unit is most appropriate.
>
> the part that's not working is that i want the code to know if it
> should use a plural or not, so for it to return "day" if there is
> only one, and "days" if there are more, for example. except at the
> moment it's making everything a plural!
>
> this is the code, apologies if it is offensive to the eye: :)
>
> def format_time seconds
> hours  = (seconds / (60 * 60))
> plural = "s" if hours.to_i > 1
> time = "#{hours.to_i} hour#{plural}"
> if hours > 23
>  days = hours / 24
>  plural = "s" if days.to_i > 1
>   time = "#{days.to_i} day#{plural}"
>   if days > 30
>    weeks = days / 7
>   plural = "s" if weeks.to_i > 1
>    time = "#{weeks.to_i} week#{plural}"
>   end
> end
>
> time
> end
>
>
> and i've got a suspicion some of this would be better with the use of
> 'yield' and blocks, except i've thoroughly messed those up as well!
>
> any help would be much appreciated.
>
> thanks
> luke

The way I did this once was to have two arrays, one containing factors and 
the other containing corresponding unit names.  That way the transformation 
really becomes a loop - and it's easy to adapt.  For example, you can have 
another array with unit names for amount of 1.  Or you create a hash from 
amont to unit names with a default for multiple thus giving you even more 
flexibility.

Kind regards

    robert