Problem with aliasing String#index

N

Niklas Frykholm

Aliasing String#index:

"rollo".index(/../, 1)
puts "noalias #{$~}"

class String
alias old_index index

def index(*arg)
ret = old_index(*arg)
puts "inside #{$~}"
return ret
end
end

"winni".index(/../, 3)
puts "outside #{$~}"

gives

noalias ol
inside ni
outside ol

To fully duplicate the functionality of the built-in String#index I need
to transfer $~ from the local scope to the enclosing scope. Is there any
way of doing this?

// Niklas
 
F

Florian Gross

Niklas said:
To fully duplicate the functionality of the built-in String#index I need
to transfer $~ from the local scope to the enclosing scope. Is there any
way of doing this?

There's a solution in the ruby-talk:79283 thread that was posted by
matz, but it's not thread safe. It would be wonderful if we could have a
proper way of doing this...
 
N

Niklas Frykholm

There's a solution in the ruby-talk:79283 thread that was posted by
matz, but it's not thread safe. It would be wonderful if we could have
a proper way of doing this...

Ah... interesting... but that technique doesn't really work with
String#index, since String#index doesn't take a block.

I think I just have to resign from the idea of making a completely
transparent String wrapper.

But it would be nice if this was resolved. In principle, I think it
should be possible to do the same things from Ruby as from C. I.e. if C
can set a variable $~ in the caller's scope, it should be possible to do
that from Ruby as well.

// Niklas
 
P

Patrick Hurley

Thanks for that code, I was lurking reading this thread and have been
wondering all day how to implement that, because of you I will get a
good nights sleep.

pth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top