I’m looking for a bit of help. I can’t seem to get the block to “pass
through” to the parent class. I figured without an ‘&’ in the parameter
list there would be no conversion to proc but maybe that is not the
case.
class Nstring < String
def gsub!(*args)
super
end
end
This works as I expected:
s = Nstring.new(“hi”)
s.gsub!(/(hi)/,’\1’)
=> “hi”
irb(main):028:0> s = NString.new(“hi”)
replicate your results:
class NString < String
def gsub!(*args, &blk)
super(*args, &blk)
end
end
=> nil
your problem has nothing to do with passing the block along in gsub!
s = NString.new(“hi”)
guess what s is here?
If you guessed “”, you guessed correctly
=> “hi”
s.gsub!(/(hi)/){$1}
=> “”
normal given that s was “”
Probably subclassing is not what you want, but it can be accomplished of
course
Here is the final solution
class NString < String
def initialize str
replace str
end
def gsub! *args
super( *args, &Proc::new ) # that is just to show you yet another
way to do this but passing &blk is better
end
end
n = Nstring::new( “123”)
p n
p n.gsub!(/…/){ |m| m.reverse } # $1 is not set as somebody did
point out already
class NString < String
end
=> nil
n = NString.new(“hi”)
=> “hi”
puts n
hi
That having been said, I generally avoid sub-classing core Ruby
objects because I think some of them use optimizations that cause
internal C methods to be called rather than the methods of a subclass,
resulting in strange behaviour. That having been said, I don’t know
that I’ve ever seen it in practice. Does anyone have an example of
this, or am I just being paranoid?
irb(main):028:0> s = NString.new(“hi”)
replicate your results:
Sorry, it seems that my $1 was set by previous tests in IRB
The others are right and the discussion has been interesting.
It also shows you have to be careful with tests in IRB…
On Fri, Aug 1, 2008 at 7:54 AM, Jesús Gabriel y
Galán[email protected] wrote:
Sorry, it seems that my $1 was set by previous tests in IRB
The others are right and the discussion has been interesting.
It also shows you have to be careful with tests in IRB…
I know that and I still managed to screw up my String subclass
constructor :-(. But I agree, interesting thread, always
good to refresh some “basic” things.
Cheers
Robert
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.