Ruby output formater

Hello,
I need to display number in 3 digit instead by defaul digit.
e.g.
val = 5
puts “#{val}”

will give me answer as 5
but need to display output in 3 digit only like 005.

Can anyone suggest me solution for this.

Thanks,
raju

Is this what you want?

val = 5
=> 5

puts “#{val}”.rjust(3,‘0’)
005

Mayank

On Mon, Jul 18, 2011 at 7:52 AM, raju sathliya
[email protected]wrote:

Thanks,
raju


Posted via http://www.ruby-forum.com/.

You want printf class IO - RDoc Documentation There
is a
breakdown of everything it can do on sprintf
module Kernel - RDoc Documentation

In this particular case, it would be printf('%03d', val)

Josh C. wrote in post #1011386:

On Mon, Jul 18, 2011 at 7:52 AM, raju sathliya
[email protected]wrote:

Thanks,
raju


Posted via http://www.ruby-forum.com/.

You want printf class IO - RDoc Documentation There
is a
breakdown of everything it can do on sprintf
module Kernel - RDoc Documentation

In this particular case, it would be printf('%03d', val)

Thanks Josh for reply !
But for variable it gives me below error

test2.rb:46: syntax error, unexpected ‘,’, expecting ‘)’
sprintf (‘%03d’,“#{num}”)
^
test2.rb:46: syntax error, unexpected ‘)’, expecting $end

Do you have any solution for this please

On Mon, Jul 18, 2011 at 8:28 AM, raju sathliya
[email protected]wrote:

  1. You shouldn’t have spaces between your method calls and the
    parentheses
    (note that you can omit the parens)
  2. printf sends result to stdout, sprintf returns the string. If you
    just
    want a string, then sprintf is right (or the % operator as Steve showed
    above), but in your example earlier, you were trying to print it.
  3. When you do “#{num}” you end up converting num into a string. There
    is no
    need for this as the “d” tells it you will be passing a number.

Steve K. wrote in post #1011390:

I personally find % cleaner than printf:

puts “%03d” % val

Why is that? As soon as you start using this with multiple arguments it
will look ugly:

puts “%03d: %-30s [%4d]\n” % [val, label, level]

vs.

printf “%03d: %-30s [%4d]\n”, val, label, level

Plus, printf is potentially more efficient since the implementation does
not need to create a Ruby String object (which is what happens with %
which is basically just a short notation for sprintf).

Kind regards

robert

I dunno, I find it conceptually cleaner, and aesthetically more
pleasing. Formatting separate from I/O.

TMTOWTDI!

Steve K. wrote in post #1011443:

I dunno, I find it conceptually cleaner, and aesthetically more
pleasing. Formatting separate from I/O.

TMTOWTDI!

Absolutely! I was just being curious.

Cheers

robert

I personally find % cleaner than printf:

puts “%03d” % val