Martin DeMello
3/15/2007 9:59:00 PM
On 3/16/07, Paul <tester.paul@gmail.com> wrote:
>
> Background context: @rawfields is an array that holds the contents of
> an imported line from a text file. Here are some sample lines from
> the input file:
> ---
> "0" "0" "0" "0" "0" "0" "Bar"
> "5.66666" "0" "3.566662" "1.383332" "6" "0" "Foo"
>> rawfields = ["5.66666", "0", "3.566662", "1.383332", "6", "0", "Foo"]
=> ["5.66666", "0", "3.566662", "1.383332", "6", "0", "Foo"]
>> rawfields.map {|field| "%0.2f" % Float(field) rescue field}
=> ["5.67", "0.00", "3.57", "1.38", "6.00", "0.00", "Foo"]
Breaking it up,
Float(string) either converts a string to a float, or raises an
exception if it cannot be so converted.
% is the sprintf operator, so "%0.2f" % float rounds the float to two
decimal places and interpolates it into the string. Note that it does
round properly, as per the printf spec, rather than truncating.
finally, expression1 rescue expression2 means return expression1,
unless it raises an exception in which case return expression2
martin