Florian Groß
4/1/2005 12:07:00 AM
Douglas Livingstone wrote:
> I want to make strings like this:
>
> $100.00 plus $22.00 per month
> $100.00
> $22.00 per week
> free (I want this when both numbers are zero)
>
> Generally: [one off fee] plus [fee per billing cycle] per [billing cycle length]
>
> I have working code, and in any other language I'd take the uglyness
> for granted, but in Ruby I still have hope. So, what would be a better
> way to write this? I've put the code I put together at the bottom.
I'll try to start from scratch so please point any errors I might have
introduced:
# Note that this is not designed to work properly with Floats as it
# directly compares to 0 -- use a delta if it also should work with
# Floats.
def human_price(currency, base_fee, cycle_fee, cycle_length)
has_base_fee = base_fee != 0
has_cycle_fee = cycle_fee != 0
result = ""
result << "%s%.2f" % [currency, base_fee] if has_base_fee
if has_cycle_fee then
result << " plus " if has_base_fee
result << "%s%.2f per %s" % [currency, cycle_fee, cycle_length]
end
result = "free" if result.empty?
return result
end
The formating of a single price could be out-factored, but I think in
this simple case it is still reasonable to just have the logic two times
in the method...