From: Lionel Bouton Date: 2007-09-11T19:57:34+09:00 Subject: Re: Substitution with Hash Lionel Bouton wrote the following on 11.09.2007 12:48 : > Lee Jarvis wrote the following on 11.09.2007 12:41 : > >> Ok i'll try to explain what i mean as well as i can >> >> Lets say i have a hash like this >> >> hash { 'a' => '1' } #just as example, its actually far bigger >> >> and if a user inputs abcdabcd i was it to sub all of the a's with 1's.. >> >> As i said, the hash is far larger which is why i can't just do it with >> gsub.. >> >> Any ideas? >> >> Thanks in advance.. >> >> Lee >> >> > > yourstring.split(//).map{|c| hash[c] || c}.join > > Note that if your hash is only used to convert single characters to single characters, you can use String#tr (or tr!). If you are after performance, as you must prepare the strings used by String#tr from your hash, you'll have to bench it to see if it's worth it in your use case even if String#tr is faster in itself. If you are processing UTF-8 content, String#tr is probably not safe (there are libraries out there for fixing this though IIRC), but my first answer probably is (assuming $KCODE='u'; require 'jcode'...) as the regexp processing is utf-8 aware, so the String#split should be safe. Lionel