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
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
=> 5puts “#{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 DocumentationIn 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:
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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs