How to write a destructive string method?

H

Henrik

I haven't been able to figure out how to write a destructive string
method of my own. How do I change the value of "self"? This is what I
tried first:

class String
alias_method:)orig_upcase, :upcase)

def upcase
orig_upcase.tr("åäö", "ÅÄÖ")
end

def upcase!
self = self.upcase
end
end

"upcase" works fine but "upcase!" doesn't - "can't change the value of
self". Nor can I do (assuming another alias_method):

def upcase!
self.old_upcase!
self.tr!("åäö", "ÅÄÖ")
end

or the same thing chained (self.old_upcase!.tr!(...)), because that only
returns nil. I've even grasped for straws like

def upcase!
=(self.upcase)
end

with no luck. Very grateful for any help.
 
D

Devin Mullins

Henrik said:
I haven't been able to figure out how to write a destructive string=20
method of my own. How do I change the value of "self"?
ri String#replace

I don't know if that'll help, 'cause I don't know why this didn't work:
def upcase!
self.old_upcase!
self.tr!("=C3=A5=C3=A4=C3=B6", "=C3=85=C3=84=C3=96")
end
=20
Devin
 
F

Fritz Heinrichmeyer

Henrik said:
I haven't been able to figure out how to write a destructive string
method of my own. How do I change the value of "self"? This is what I
tried first:

it makes no sense to change self, but you can change the data of self:

---- test.rb
class String
def makefirstA
self[0]= 65
self
end
end

x="xxxx"
p x.makefirstA
p x
--- end of test.rb

delivers

ruby test.rb
"Axxx"
"Axxx"
 
H

Henrik

ts said:
H> def upcase!
H> self = self.upcase

replace(upcase)

H> end
H> end


Guy Decoux

Worked fine, thanks! Got some help on #ruby-lang, apparently you can do
stuff like the above and

self[0..-1] = "whatever"
but not
self = "whatever"

seeing as self is an object, not a variable - if anyone else was
wondering.
 
F

Florian Groß

Henrik said:
Nor can I do (assuming another alias_method):
=20
def upcase!
self.old_upcase!
self.tr!("=C3=A5=C3=A4=C3=B6", "=C3=85=C3=84=C3=96")
end
=20
or the same thing chained (self.old_upcase!.tr!(...)), because that onl= y=20
returns nil.

I'd do it like this: (Ignoring the more obvious replace solution)

class String
alias :eek:ld_upcase! :upcase!
def upcase!()
old_upcase!
tr!("=C3=A5=C3=A4=C3=B6", "=C3=85=C3=84=C3=96")
end

def upcase()
result =3D self.clone
result.upcase!
return result
end
end

--=20
http://flgr.0x42.net/
 

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,780
Messages
2,569,611
Members
45,282
Latest member
RoseannaBa

Latest Threads

Top