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...
PS) There's a full list of the supported format codes
HERE.