like
[["Customer", "John", 84.95, ["USE", 10.0]], ["IN", 84.95], ["USE",
94.95], ["OUT", 94.95]]
I tried with pp, but it does not truncate floats. Items in Array can be
arbitary in length.
Yes, pp gives a precise representation of the object as much as
possible, and I like it this way...
In similar situation I just use the following hack:
x # => 45.235234
(100 * x).to_i.to_f / 100 # => 45.23
You can make a float method of it to hide the clutter :)
But maybe there is a better way...
I see you want to do it recursively, but I guess that's not a problem to
implement.
Csaba
Not 100% what you want though...
conv = lambda do |e|
case e
when String
e
when Enumerable
e.map &conv
when Float
sprintf( "%3.2f", e )
else
e
end
end
a= [["Customer", "John", 84.9535929148379, ["USE", 10.0]], ["IN",
84.9535929148379], ["USE", 94.9535929148379], ["OUT",
94.9535929148379]]
a.map &conv
?> a.map &conv
=> [["Customer", "John", "84.95", ["USE", "10.00"]], ["IN", "84.95"],
["USE", "94.95"], ["OUT", "94.95"]]
inj = lambda do |(f,s),e|
s << ", " if f
case e
when String
s << e.inspect
when Enumerable
s << "["
e.inject([false, s], &inj)
s << "]"
when Float
s << sprintf( "%3.2f", e )
else
s << e.inspect
end
[true,s]
end
puts( a.inject([false, ""],&inj)[1] << "]" )
>> puts( a.inject([false, ""],&inj)[1] << "]" )
["Customer", "John", 84.95, ["USE", 10.00]], ["IN", 84.95], ["USE", 94.95],
["OUT", 94.95]]
Better. As usual - with #inject... :-)
Kind regards
robert
Ugly, but if this is just for debugging purposes you can do the
following:
class Float
def inspect
if $truncate
#round to $truncate places
else
self.to_s
end
end
end
and depending on the global it'll round off or not
martin