array formatting

For general discussion related FlowStone
Post Reply
tester
Posts: 1786
Joined: Wed Jan 18, 2012 10:52 pm
Location: Poland, internet

array formatting

Post 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.
Need to take a break? I have something right for you.
Feel free to donate. Thank you for your contribution.
User avatar
trogluddite
Posts: 1730
Joined: Fri Oct 22, 2010 12:46 am
Location: Yorkshire, UK

Re: array formatting

Post 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 869 times


PS) There's a full list of the supported format codes HERE.
All schematics/modules I post are free for all to use - but a credit is always polite!
Don't stagnate, mutate to create!
Post Reply