Simply Ruby question: "zerofill"


#1

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


#2

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)


#3

This is what I would use:

val=43
n=8
val2="%0#{n}d" % [val]


#4

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?


#5

ri String#%

C:\Documents and Settings\Owner\Desktop\MyRuby\Quiz\59>ri String#%
--------------------------------------------------------------- String#%
str % arg => new_str

 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"

#6

On 12/19/05, Jake J. removed_email_address@domain.invalid 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.


#7

$ irb
irb(main):001:0> “%08d” % [43]
=> “00000043”

Kent.


#8

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


#9

On 12/19/05, Jake J. removed_email_address@domain.invalid 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