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.
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:
This may or may not run faster than my first solution, but the first
is easier to code/maintain.
Jeremy
···
On Sep 27, 12:18 pm, Michael Linfield <globyy3...@hotmail.com> 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.
words = gets.chomp
new = subs.inject(words) {|acc, sub| acc.gsub(sub[0], sub[1])} unless
words.nil?
or:
words = gets.chomp
new = words.gsub('h', '00').gsub('i', '01').gsub('j', '02') unless
words.nil?
Hopefully that's right.
Jeremy
Haha no worries, thanks a ton -- didnt know you could chain gsubs but
now i think ill go with the inject method cause yes you were right when
you talked about maintaining it.