I'm attempting to create a substitution translator for a language my friend and I created. In this language, certain things have to happen simultaneously and I can't figure out how to do that in Ruby.
With simple things like swapping the vowels around, i.e.
a --> u
i --> o
o --> i
u --> a
I've just done this:
input.tr("aiou", "uoia")
But I can't figure out a way to make the following translations occur simultaneously:
no --> e
e --> y
y --> el
so that the phrase "yellow rhino" would become "elyllow rhie".
Any suggestions or examples for what I can do? gsub? tr? Another method altogether?
First you define a substitution map:
MAP = {
'a' => 'u',
'i' => 'o',
'o' => 'i',
'u' => 'a',
'y' => 'el',
'no' => 'e',
'e' => 'y'
}
Then you can make this into a regular expression to match all the "keys" in one shot:
SUBST = Regexp.union(MAP.keys)
This is handy because gsub can use these mapping tables to do substitution:
def translate(words)
words.gsub(SUBST, MAP)
end
Which means you can do this:
puts translate("translate multiple words simultaneously")
# => trunsluty maltoply wirds somaltunyiaslel
tr is a great tool, but it's limited to single character substitutions. gsub can do everything tr can and more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With