Weird thing with "sub" and "rjust"

I would like to write code which does the following transformations:

  "hello-3.jpg" => "hello-003.jpg"
  "hello-42.jpg" => "hello-042.jpg"
  "hello-250.jpg" => "hello-250.jpg"

And I tried this:

  string.sub(/(\d+)/, '\1'.rjust(3, '0'))

where "string" is one of the above strings (in the left side of =>).

It works with:

  'hello-42.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-042.jpg"

But it doesn't works with:

  'hello-3.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-03.jpg"

And doesn't works with:

  'hello-250.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-0250.jpg"

What's wrong?

Thanks a lot.

Dunno, but:

.sub(/(\d+)/) { $1.rjust 3, '0' }

seems to do the trick.

···

On Oct 25, 2005, at 12:52 PM, ricpelo@gmail.com wrote:

I would like to write code which does the following transformations:

  "hello-3.jpg" => "hello-003.jpg"
  "hello-42.jpg" => "hello-042.jpg"
  "hello-250.jpg" => "hello-250.jpg"

And I tried this:

  string.sub(/(\d+)/, '\1'.rjust(3, '0'))

where "string" is one of the above strings (in the left side of =>).

It works with:

  'hello-42.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-042.jpg"

But it doesn't works with:

  'hello-3.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-03.jpg"

And doesn't works with:

  'hello-250.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-0250.jpg"

What's wrong?

--
Eric Hodel - drbrain@segment7.net - http://segment7.net
FEC2 57F1 D465 EB15 5D6E 7C11 332A 551C 796C 9F04

The rjust is being evaluated before the sub call, so what you've
written is equivalent to this:

'hello-3.jpg'.sub(/(\d+)/, "0\\1")

Use the block form instead:

'hello-3.jpg'.sub(/(\d+)/) { $1.rjust(3, '0')}
=> "hello-003.jpg"

regards,
Ed

···

On Wed, Oct 26, 2005 at 04:52:02AM +0900, ricpelo@gmail.com wrote:

But it doesn't works with:

  'hello-3.jpg'.sub(/(\d+)/, '\1'.rjust(3, '0'))
  => "hello-03.jpg"