Stuff method

Hi,

I missed the stuff function or method found in some languages so I added
this method to my Helpers mixin.

def stuff(str, substr, rplstr, prefix = ‘.’)
r1 = Regexp.new("(#{prefix})(#{substr})(.
)")
str.gsub(r1,’\1’+rplstr+’\3’)
end

puts stuff(‘012-014640-001’,’-.’,’-X’)

This works but if you know a better way please share so I can learn.

In particular it would be nicer I think if it worked like this:

new_str = ‘012-014640-001’.stuff(’-.’,’-X’)

Thanks,
Carl

On Jan 23, 2008 7:23 PM, Carl G. [email protected] wrote:

puts stuff(‘012-014640-001’,’-.’,’-X’)

This works but if you know a better way please share so I can learn.

In particular it would be nicer I think if it worked like this:

new_str = ‘012-014640-001’.stuff(’-.’,’-X’)

Try this if you want it to work like above. You should always be careful
when modifying core classes, yada yada yada…

class String
def stuff(substr, rplstr, prefix = ‘.’)
r1 = Regexp.new("(#{prefix})(#{substr})(.
)")
self.gsub(r1,’\1’+rplstr+’\3’)
end
end

Michael G.

Michael G. wrote:

On Jan 23, 2008 7:23 PM, Carl G. [email protected] wrote:

puts stuff(‘012-014640-001’,’-.’,’-X’)

This works but if you know a better way please share so I can learn.

In particular it would be nicer I think if it worked like this:

new_str = ‘012-014640-001’.stuff(’-.’,’-X’)

Try this if you want it to work like above. You should always be careful
when modifying core classes, yada yada yada…

class String
def stuff(substr, rplstr, prefix = ‘.’)
r1 = Regexp.new("(#{prefix})(#{substr})(.
)")
self.gsub(r1,’\1’+rplstr+’\3’)
end
end

Michael G.

Thanks Michael!

I guess the use of self is because gsub is itself a member of String.
Just out of curiosity I wonder if I can use
String.gsub(r1,’\1’+rplstr+’\3’) as well - but even should that work I’m
sure it is unorthodox.

Carl

Carl G. wrote:

puts stuff(‘012-014640-001’,’-.’,’-X’)

This works but if you know a better way please share so I can learn.

In particular it would be nicer I think if it worked like this:

new_str = ‘012-014640-001’.stuff(’-.’,’-X’)

How about:

s = ‘012-014640-001’
puts s.gsub(/(.)-.(.)/, “\1-X\2”)
puts s.gsub(/(.)-.(.)/) { “#{$1}-X#{$2}” }

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs