Unexpected sprintf/String % Behavior

Hello,

I am puzzled by some strange (to me) behavior exhibited by String's % method as well as sprintf. Both "%02d" % "07" and sprintf("%02d","07") output "07". However, "%02d" % "08" and sprintf("%02d","08") both raise 'ArgumentError: invalid value for Integer: "08"'. Why does a string of "07" work while "08" does not?

This is true when I test this on a MS Windows XP Pro box running Ruby 1.6.8 and when I test it on a Debian Woody box (kernal 2.4.19) running Ruby 1.8.2. IRB examples and results are below.

Thank you,
Ben

Win XP box

···

-------------
irb(main):014:0> "%02d" % "07"
=> "07"
irb(main):015:0> "%02d" % "08"
ArgumentError: invalid value for Integer: "08"
        from (irb):15:in `%'
        from (irb):15
irb(main):017:0> sprintf("%02d","07")
=> "07"
irb(main):018:0> sprintf("%02d","08")
ArgumentError: invalid value for Integer: "08"
        from (irb):18:in `sprintf'
        from (irb):18

Linux box
----------
irb(main):003:0> "%02d" % "07"
=> "07"
irb(main):004:0> "%02d" % "08"
ArgumentError: invalid value for Integer: "08"
        from (irb):4:in `%'
        from (irb):4

irb(main):005:0> sprintf("%02d","07")
=> "07"
irb(main):006:0> sprintf("%02d","08")
ArgumentError: invalid value for Integer: "08"
        from (irb):6:in `sprintf'
        from (irb):6

Ben Gribaudo wrote:

Hello,

I am puzzled by some strange (to me) behavior exhibited by String's % method as well as sprintf. Both "%02d" % "07" and sprintf("%02d","07") output "07". However, "%02d" % "08" and sprintf("%02d","08") both raise 'ArgumentError: invalid value for Integer: "08"'. Why does a string of "07" work while "08" does not?

Because leading 0 makes your argument string be interpreted as an octal number, where '8' is not a valid digit (0..7 are valid in base 8).

Hope it helps.
Gennady.

leading zeros (as in c) mean octal. so there is no 08. only

   00 01 02 03 04 05 06 07

the number eight being 10

for instance

   harp:~ > irb
   irb(main):001:0> 010
   => 8

   irb(main):002:0> 017
   => 15

   irb(main):003:0> 08
   SyntaxError: compile error
   (irb):3: Illegal octal digit
           from (irb):3

not that you also have hex and binary literals like

   0xa
   0b101010

hth.

-a

···

On Thu, 16 Jun 2005, Ben Gribaudo wrote:

Hello,

I am puzzled by some strange (to me) behavior exhibited by String's % method as well as sprintf. Both "%02d" % "07" and sprintf("%02d","07") output "07". However, "%02d" % "08" and sprintf("%02d","08") both raise 'ArgumentError: invalid value for Integer: "08"'. Why does a string of "07" work while "08" does not?

--

email :: ara [dot] t [dot] howard [at] noaa [dot] gov
phone :: 303.497.6469
My religion is very simple. My religion is kindness.
--Tenzin Gyatso

===============================================================================

Thank you for explaining this.

Ben