Hi there-
What’s the easiest/most efficient way to perform a zerofill in Ruby?
i.e. Given the value ‘val’, I would like to do something like:
val = 43
puts val.zerofill(8)
—> “00000043”
gsub? sprintf of some sort?
Jake
Hi there-
What’s the easiest/most efficient way to perform a zerofill in Ruby?
i.e. Given the value ‘val’, I would like to do something like:
val = 43
puts val.zerofill(8)
—> “00000043”
gsub? sprintf of some sort?
Jake
Jake J. wrote:
Hi there-
What’s the easiest/most efficient way to perform a zerofill in Ruby?
i.e. Given the value ‘val’, I would like to do something like:val = 43
puts val.zerofill(8)
—> “00000043”gsub? sprintf of some sort?
Jake
sprintf("%08d", val)
This is what I would use:
val=43
n=8
val2="%0#{n}d" % [val]
Kent S. wrote:
$ irb
irb(main):001:0> “%08d” % [43]
=> “00000043”Kent.
Thanks much. Where is this syntax documented? Is it just a convenient
way to call sprintf or is it another method?
ri String#%
Format---Uses _str_ as a format specification, and returns the
result of applying it to _arg_. If the format specification
contains more than one substitution, then _arg_ must be an +Array+
containing the values to be substituted. See +Kernel::sprintf+ for
details of the format string.
"%05d" % 123 #=> "00123"
"%-5s: %08x" % [ "ID", self.id ] #=> "ID : 200e14d6"
On 12/19/05, Jake J. [email protected] wrote:
Kent S. wrote:
$ irb
irb(main):001:0> “%08d” % [43]
=> “00000043”Kent.
Thanks much. Where is this syntax documented? Is it just a convenient
way to call sprintf or is it another method?
It’s a call to sprintf, or I suppose more accurately, a call to:
sprintf(format_string, *values)
The parameter to the right of the % sign can either be a single value,
or an Array, if there are multiple positions to fill in the format
string.
Other than that, it’s identical to sprintf.
–Wilson.
$ irb
irb(main):001:0> “%08d” % [43]
=> “00000043”
Kent.
On Mon, 19 Dec 2005, Jake J. wrote:
Kent S. wrote:
$ irb
irb(main):001:0> “%08d” % [43]
=> “00000043”Kent.
Thanks much. Where is this syntax documented? Is it just a convenient
way to call sprintf or is it another method?
http://www.rubycentral.com/book/ref_c_string.html#String._pc
On 12/19/05, Jake J. [email protected] wrote:
Hi there-
What’s the easiest/most efficient way to perform a zerofill in Ruby?
i.e. Given the value ‘val’, I would like to do something like:val = 43
puts val.zerofill(8)
—> “00000043”gsub? sprintf of some sort?
“%08d” % 43
=> “00000043”
–
sam
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