I was stuck on a problem, and a friend sent me a solution without time to explain such. I’d like to come back to this problem and learn a little more from it. I was just wondering if someone could help me with a quick run down of specific aspects of this code.
def translate phrase
phrase.split.map do |word|
word =~ /^([^aeiouyq]*(qu)?)(.*)$/
first_translation = $1
rest_of_translation = $3
"#{rest_of_translation}#{first_translation}ay"
end.join(" ")
end
I don’t quite grasp the concept of how I substituted letters. The line I’m referring to is words =~
Related to this, I know $ refers to the chunks of my expression. Yet, I’m not quite sure I know how I obtained them.
This is a simple Pig Latin translator. The code works in several steps:
IRB is very helpful for analyzing snippets of code like this.
The
$1,$2,$3, etc. variables are special global variables that capture matches in parentheses in the regular expression. They don’t necessarily stick around for very long, so if you use them you should assign them to something else right away.