我定義的豬拉丁語翻譯方法有兩種:convert_word_to_pig_latin方法是將每個單詞轉換成隱語,及convert_sentence_to_pig_latin方法是使用convert_word_to_pig_latin方法的句子。
def convert_word_to_pig_latin(word)
vowels = "aeiou"
punctuations = ".,?!'\":;-"
if vowels.include?(word[0])
return word
else
if punctuations.include?(word[-1])
punctuation = word[-1]
word = word.chop
end
first_vowel_index = word.chars.find_index { |letter| vowels.include?(letter) }
new_word = word[first_vowel_index..-1] + word[0...first_vowel_index] + "ay"
return punctuation ? new_word += punctuation : new_word
end
end
def convert_sentence_to_pig_latin(sentence)
sentence_array = sentence.split(" ")
sentence_array.map { |word| convert_word_to_pig_latin(word) }.join(" ")
end
注:請隨意添加任何額外的標點符號,只要你願意。
最後,這裏是我的RSpec的,以確保我的兩個方法,通過所有的測試:
require_relative('../pig_latin')
describe 'Converting single words to Pig Latin' do
word1 = "beautiful"
word2 = "easy"
word3 = "straight"
it "converts word to Pig Latin" do
expect(convert_word_to_pig_latin(word1)).to eq "eautifulbay"
end
it "does not change word if it begins with a vowel" do
expect(convert_word_to_pig_latin(word2)).to eq "easy"
end
it "converts word to Pig Latin" do
expect(convert_word_to_pig_latin(word3)).to eq "aightstray"
end
end
describe 'Converting a sentence to Pig Latin' do
sentence1 = "Make your life a masterpiece; imagine no limitations on what you can be, have, or do."
sentence2 = "The pessimist sees difficulty in every opportunity. The optimist sees the opportunity in every difficulty."
it "converts motivational quote from Brian Tracy to Pig Latin" do
expect(convert_sentence_to_pig_latin(sentence1)).to eq "akeMay ouryay ifelay a asterpiecemay; imagine onay imitationslay on atwhay ouyay ancay ebay, avehay, or oday."
end
it "converts motivational quote from Winston Churchill to Pig Latin" do
expect(convert_sentence_to_pig_latin(sentence2)).to eq "eThay essimistpay eessay ifficultyday in every opportunity. eThay optimist eessay ethay opportunity in every ifficultyday."
end
end
這主要是你想用來代表解析句子什麼樣的結構的問題。 –
你是什麼意思? – Raph
那麼,你的問題在於你有一個通過分割一些較大的字符串獲得的單詞列表,但這些單詞在其中有標點符號。你可以通過刪除所有的標點符號來解決這個問題,但是你最終無法得到它。因此,您需要一種方法來表示數據結構中原始字符串的所有信息,這些信息比簡單的字符串更易於使用。 –