From: Bill Guindon Date: 2006-02-15T08:44:12+09:00 Subject: Re: simple programming q On 2/14/06, grrr wrote: > 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 ) Here's a simple answer, using a regular expression. blokoftxt = 'Theres some text in block.' replacekey = { 'T' => 'W', 'a' => 'o', 'o' => 'b' } replacekey.each {|key, val| blokoftxt.gsub!(/#{key}/, val)} > 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 > > > > -- Bill Guindon (aka aGorilla) The best answer to most questions is "it depends".