simple programming q

G

grrr

I am a ruby newbie. I want to make a simple script that replaces certain
characters in a block of text with specific other characters.

I am wondering what kind of loop or algo is thought to be most effective
for this kind of work..
Maybe go through the block of text with a hashing table and replace
each 'hit'? Would this be reasonable approach?

#example pseudocode idea
blokoftxt = 'Theres some text in block.'
replacekey = { 'T' = 'W', 'a' = 'o', 'o' = 'a' }

blokoftxt.each ( if equal to a replacekey, replace with key value )


This would mean going through each character in the textblock. I guess one
could conversely go through the replacekey array and match to the
textblock?? Which way to go?

J Von Rubiginner
 
B

Bill Guindon

I am a ruby newbie. I want to make a simple script that replaces certain
characters in a block of text with specific other characters.

I am wondering what kind of loop or algo is thought to be most effective
for this kind of work..
Maybe go through the block of text with a hashing table and replace
each 'hit'? Would this be reasonable approach?

#example pseudocode idea
blokoftxt =3D 'Theres some text in block.'
replacekey =3D { 'T' =3D 'W', 'a' =3D 'o', 'o' =3D 'a' }

blokoftxt.each ( if equal to a replacekey, replace with key value )

Here's a simple answer, using a regular expression.

blokoftxt =3D 'Theres some text in block.'
replacekey =3D { 'T' =3D> 'W', 'a' =3D> 'o', 'o' =3D> 'b' }
replacekey.each {|key, val| blokoftxt.gsub!(/#{key}/, val)}
 
E

Eric Hodel

I am a ruby newbie. I want to make a simple script that replaces
certain
characters in a block of text with specific other characters.

I am wondering what kind of loop or algo is thought to be most
effective
for this kind of work..
Maybe go through the block of text with a hashing table and replace
each 'hit'? Would this be reasonable approach?

#example pseudocode idea
blokoftxt = 'Theres some text in block.'
replacekey = { 'T' = 'W', 'a' = 'o', 'o' = 'a' }

blokoftxt.each ( if equal to a replacekey, replace with key value )

blokoftxt.tr 'Tao', 'Woa'
 
G

grrr

Re:
Haha! That's awesome. (sorry, I'm easily amused)

-Harold

Yes indeed! Hehe I guess I am easily amused, too!

Thats pretty much the solution I was looking for, even if I was expecting
replies from Knuths books. Thanks Eric!
 

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
474,202
Messages
2,571,057
Members
47,664
Latest member
RoseannBow

Latest Threads

Top