From: "yermej@..." Date: 2007-09-28T03:45:06+09:00 Subject: Re: gsub-ing each character On Sep 27, 12:18 pm, Michael Linfield wrote: > I want to convert certain letters to numbers on a gets.chomp.. > my initial approach was this---- > > words = gets.chomp > new = words.each {|p| p.gsub(/[h]/, '00')} > > puts new > > ##### > however this doesnt work the miracle :) > > new = words.gsub(/[h]/, '00') > > puts new > > ##### this works perfectly, but the problem occurs if i want to gsub > more than one character as if i have new = another.gsub then puts new > only outputs the last gsub. > > Ideas? > > Thanks! > -- > Posted viahttp://www.ruby-forum.com/. Normally, you'd use String#tr for something like this, but since you want to replace single characters with multiple characters, you might try something like this: subs = { 'h' => '00', 'i' => '01', 'j' => '02', } new = gets.chomp subs.inject(new) {|acc, sub| acc.gsub(sub[0], sub[1])} unless new.nil? For something more similar to what you're already doing, you can chain the #gsub calls together: new.gsub('h', '00').gsub('i', '01').gsub('j', '02') unless new.nil? This may or may not run faster than my first solution, but the first is easier to code/maintain. Jeremy