Skip to content

Instantly share code, notes, and snippets.

@jcsalterego
Forked from zachgersh/pig_latin.rb
Last active December 15, 2015 08:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jcsalterego/5234470 to your computer and use it in GitHub Desktop.
Save jcsalterego/5234470 to your computer and use it in GitHub Desktop.
def translate(phrase)
phrase.split.inject([]) do |final_pigs, word|
char = word.split(//)
if char[0].match(/[aeiou]/)
final_pigs << "#{word}ay"
else
new_string = char
until new_string[0].match(/[aeio]/)
new_string << new_string.shift
end
final_pigs << new_string.join + "ay"
end
final_pigs
end
end
@jcsalterego
Copy link
Author

Changes from the original:

  • Use #inject; [] is the starting value for final_pigs, and word is all the elements within phrase.split; for more information, check the docs
  • Use [0] instead of #at(0); I don't know any good reason to use #at
  • Introduced an inconsistency by using string interpolation on line 5; for complex concatentation, many rubyists use this
  • I'm not crazy about the new_string << new_string.shift line, but I can't think of a better way to do that now
  • At the end of the #inject block, final_pigs is used as basically an implicit return of what the next final_pigs values should be; this is part of the usage of #inject

@zachgersh
Copy link

thanks @jcsalterego Really interesting use of inject! I really hadn't considered doing the summation of [ ] and word.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment