Page 1 of 1

array formatting

Posted: Fri Dec 13, 2013 9:20 pm
by tester
How to format array of floats using ruby?
Equivalent of "format string" primitive.
For example trim array values to 0.00 or set display like 000.00 and so on.

Re: array formatting

Posted: Sat Dec 14, 2013 11:38 am
by trogluddite
tester wrote:Equivalent of "format string" primitive...

...is the 'format' method. It uses exactly the same format codes as the primitive - which you give as the first argument (in the form of a string), followed by the value that needs formatting... e.g.

Code: Select all

@x = Math::PI
format( "%.3f", @x)   #=>  "3.142"


You can include more than just the '%' codes too...

Code: Select all

format("The value of PI is %.3f approximately", @x)  #=> "The value of PI is 3.142 approximately"


Or include multiple '%' codes and a list of substitute items to match...

Code: Select all

@x = 5.12345
@y = @x * @x
format("The square of %.3f is %.3f", @x, @y)   #=>  "The square of 5.123 is 26.250"


To do this for every item in the array, the method "collect" is the easiest way - or you can call it "map" if you're not so keen on typing! It takes every item in an array, processes it, and then places all the answers in a new array...

Code: Select all

@myArray = [1, 2, 3, 4, 5]
@format_code = "%.3f"
@formatted = @myArray.collect{|item|  format(@format_code, item)}


Here's a module based on that code that spits out both a string array and a single string of joined items...
Float Array Format.fsm
(815 Bytes) Downloaded 871 times


PS) There's a full list of the supported format codes HERE.