Support

If you have a problem or need to report a bug please email : support@dsprobotics.com

There are 3 sections to this support area:

DOWNLOADS: access to product manuals, support files and drivers

HELP & INFORMATION: tutorials and example files for learning or finding pre-made modules for your projects

USER FORUMS: meet with other users and exchange ideas, you can also get help and assistance here

NEW REGISTRATIONS - please contact us if you wish to register on the forum

Users are reminded of the forum rules they sign up to which prohibits any activity that violates any laws including posting material covered by copyright

array formatting

For general discussion related FlowStone

array formatting

Postby tester » Fri Dec 13, 2013 9:20 pm

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.
tester
 
Posts: 1786
Joined: Wed Jan 18, 2012 10:52 pm
Location: Poland, internet

Re: array formatting

Postby trogluddite » Sat Dec 14, 2013 11:38 am

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 755 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!
User avatar
trogluddite
 
Posts: 1730
Joined: Fri Oct 22, 2010 12:46 am
Location: Yorkshire, UK


Return to General

Who is online

Users browsing this forum: No registered users and 96 guests