Stuff method

C

Carl Graff

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
 
M

Michael Guterl

[Note: parts of this message were removed to make it a legal post.]

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')

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 Guterl
 
C

Carl Graff

Michael said:
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 Guterl

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
 
J

Joel VanderWerf

Carl said:
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')

How about:

s = '012-014640-001'
puts s.gsub(/(.*)-.(.*)/, "\\1-X\\2")
puts s.gsub(/(.*)-.(.*)/) { "#{$1}-X#{$2}" }
 

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

Forum statistics

Threads
474,277
Messages
2,571,385
Members
48,088
Latest member
AngieMaliz

Latest Threads

Top