I’m making a basic translator in Ruby (1.9.3). I’m pulling from a local test file (‘a.txt’) and using gsub to replace certain matches to mimic a translation from contemporary English to Middle/Early Modern English. I’ve run into a readability issue:
How can I make the large amount of gsub usage easier to read? I’ve attempted to use multiple lines starting with
def translate
@text.gsub(/my/, 'mine')
@text.gsub(/\sis\s/, ' be ')
end
but this only prints the final gsub. I can only assume that the second request overwrites the first. I would like to avoid creating a giant line of gsub requests and I cannot seem to find a suitable answer.
Here is a sample of my current program:
lines = File.readlines('a.txt')
@text = lines.join
def translate
@text.gsub(/my/, 'mine').gsub(/\sis\s/, ' be ').gsub(/y\s/, 'ye ').gsub(/t\s/, 'te ').gsub(/t\,/, 'te,').gsub(/t\./, 'te.')
end
puts translate
I apologize in advance if this request seems thoroughly basic.
Cheers!
The second call doesn’t override the first. The first call returns a copy of
@textwith the substitution made, but you aren’t doing anything with that returned value. If you want to modify@text, you need to usegsub!instead. If you don’t want to modify@text, then you need to chain thegsubcalls instead. For instance, if you have the mapping Hash from slivu’s answer, this will return the translated text without actually modifying the@textinstance variable:The block passed to
injectgets called once per mapping (key/value pair inRegexMap). The first time,stringis the value passed toinject– namely,@text. After that, each subsequent call gets the return value of the previous call passed in as itsstringvalue. So it’s as if you did this, but with the set of mappings more easily configurable: