Regexp indexes to strings

I like this, but can it be extended to work for replacing?

irb(main):001:0> a=“123-456-1239”
=> "123-456-1239"
irb(main):002:0> a[/123/]
=> "123"
irb(main):003:0> a[/123/]=“xxx”
=> "xxx"
irb(main):004:0> a
=> “xxx-456-1239”

This is good stuff. Except it doesn’t extend.

irb(main):005:0> a=“123-456-1239”
=> "123-456-1239"
irb(main):006:0> a[/123/, 2]="xxx"
IndexError: index 2 out of regexp
from (irb):6:in []=' from (irb):6 irb(main):007:0> a[/123/, 1]="xxx" IndexError: index 1 out of regexp from (irb):7:in[]='
from (irb):7
irb(main):008:0> a
=> “123-456-1239”

Bah! This would really rule.

irb(main):006:0> a[/123/, 2]=“xxx”
IndexError: index 2 out of regexp

Well, this case is for

svg% ruby -e ‘a=“123-456-1239”; a[/1(2)3/, 1] = “xxx”; p a’
“1xxx3-456-1239”
svg%

svg% ruby -e ‘a=“123-456-1239”; a[/1(2)(3)/, 2] = “xxx”; p a’
“12xxx-456-1239”
svg%

you can write

svg% ruby -e ‘a=“123-456-1239”; a[/123/] = “xxx”; p a’
“xxx-456-1239”
svg%

···

Guy Decoux

I think it doesn’t work because your regexp only has one capture group.
If you
define multiple capture groups it works just fine:

a=“123-456-1239”
a[/([0-9]{3,3})-([0-9]{3,3})-([0-9]{3,4})/,2]=“XXX”

I tested this in IRB and it seems work just fine. I don’t know if
there’s a more efficient way to do
this that is less complex looking but it does work. Let me know if you
need help decoding this regexp,
but I think it’s fairly self explanatory.

Yan

Rob Partington wrote:

···

This is good stuff. Except it doesn’t extend.

irb(main):005:0> a=“123-456-1239”
=> “123-456-1239”
irb(main):006:0> a[/123/, 2]=“xxx”
IndexError: index 2 out of regexp
from (irb):6:in []=' from (irb):6 irb(main):007:0> a[/123/, 1]="xxx" IndexError: index 1 out of regexp from (irb):7:in =’
from (irb):7
irb(main):008:0> a
=> “123-456-1239”

Bah! This would really rule.