How to format an array

Hi all,

I have an array [1.0, 2.0, 3, 4,5,6]. I want to format all the elements
within the array into to this format “%5.3f”, that is 5
spaces/characters for each number/element, followed by 3 floating
points. Any help will be appreciate.

Li

[1.0, 2.0, 3, 4,5,6].map { |num| “%5.3f” % num } #=> [“1.000”, “2.000”,
“3.000”, “4.000”, “5.000”, “6.000”]

Hello,

Li Chen wrote:

Hi all,

I have an array [1.0, 2.0, 3, 4,5,6]. I want to format all the elements
within the array into to this format “%5.3f”, that is 5
spaces/characters for each number/element, followed by 3 floating
points. Any help will be appreciate.

[1.0, 2.0, 3, 4,5,6].map { |n| sprintf “%5.3f”, n }

Peter
http://www.rubyrailways.com

On 10/19/06, Li Chen [email protected] wrote:

Hi all,

I have an array [1.0, 2.0, 3, 4,5,6]. I want to format all the elements
within the array into to this format “%5.3f”, that is 5
spaces/characters for each number/element, followed by 3 floating
points. Any help will be appreciate.

might not be the best solution, but hey it’s different from the others:

ar = [1.0, 2.0, 3, 4, 5, 6]
p sprintf "%5.3f " * ar.length, *ar

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs