2013-08-27 27 views
0

我在寫測試文件,但我不能把它通過第二次測試,在這裏:如何在Ruby中檢查字符串中的第一個字母?

def translate(word) 
    if word.start_with?('a','e','i','o','u')   
     word << "ay" 
    else   
     word << "bay" 
    end 
end 

是做這份工作的合適方法?

describe "#translate" do 

    it "translates a word beginning with a vowel" do 
    s = translate("apple") 
    s.should == "appleay" 
    end 

    it "translates a word beginning with a consonant" do 
    s = translate("banana") 
    s.should == "ananabay" 
    end 

    it "translates a word beginning with two consonants" do 
    s = translate("cherry") 
    s.should == "errychay" 
    end 
end 

編輯: 我的解決方案不完整。 我的代碼只能通過第一次測試,因爲我能夠將「ay」推到單詞的結尾。我錯過了第二個測試是刪除第一個字母,如果它的輔音,在「香蕉」中是「b」。

+2

爲什麼如果是輔音,第一個字母會被刪除?你的代碼不這樣做,因此測試不通過。 –

+0

您是否在'translate'方法中發佈了'if'表達式?測試如何失敗? – toro2k

+0

@ toro2k是的我已經def def(word)... end – egyamado

回答

5

你也可以這樣做:

word << %w(a e i o u).include?(word[0]) ? 'ay' : 'bay' 

使用正則表達式可能會在你的情況是矯枉過正,但如果你想匹配更復雜的字符串是非常方便的。

+0

當我運行耙子時,出現錯誤。 1)#translate轉換以元音 故障/錯誤開頭的單詞:S =翻譯(「蘋果」) 類型錯誤: 不能轉換成真正的字符串 – egyamado

+0

這種方法依賴於改變在Ruby中的String類1.9+(現在每個人都應該使用,但以防萬一...) – Gareth

1

看起來要刪除的第一個字符,如果單詞以輔音開始了,所以:

if word.start_with?('a','e','i','o','u') 
    word[0] = '' 
    word << 'ay' 
else 
    consonant = word[0] 
    word << "#{consonant}ay" 
end 
+0

第三個測試呢?我認爲它不起作用。 –

+0

現在,它的工作。 =] – MurifoX

+0

對不起,如果我沒有錯,在第三個測試中輸出將是「cherrycay」。但測試案例預計會「錯誤」。第二次看,第一次測試也失敗了。你的代碼的輸出是「ppleay」,但測試用例期望「appleay」。 –

1

word << word[0].match(/a|e|i|o|u/).nil? ? 'bay' : 'ay'

1

你的代碼的意思是: 如果字與( 'A' 開始,」 e','i','o','u')在末尾添加「ay」 否則在最後添加「bay」。

第二測試將是 「bananabay」 而不是 「ananabay」(用b爲第一個字母)

+0

我第一次測試通過:word <<'ay'if word.start_with?('a','e','i','o','u')。但我不能得到第二個通過,我總是在開始的字母b – egyamado

+0

這是因爲你的翻譯功能不會將其刪除。試着想一下翻譯功能需要先用英文做些什麼。然後嘗試寫在紅寶石 – Slicedpan

0

的下面一段代碼通過了所有測試...

def translate(word) 
    if word.start_with?('a','e','i','o','u') 
    word<<'ay' 
    else 
    pos=nil 
    ['a','e','i','o','u'].each do |vowel| 
     pos = word.index(vowel) 
     break unless pos.nil? 
    end 
    unless pos.nil? 
     pre = word.partition(word[pos,1]).first 
     word.slice!(pre) 
     word<<pre+'ay' 
    else 
     #code to be executed when no vowels are there in the word 
     #eg words fry,dry 
    end 
    end 
end 
1
def translate(word) 
    prefix = word[0, %w(a e i o u).map{|vowel| "#{word}aeiou".index(vowel)}.min] 
    "#{word[prefix.length..-1]}#{prefix}ay" 
end 

puts translate("apple") #=> "appleay" 
puts translate("banana") #=> "ananabay" 
puts translate("cherry") #=> "errychay" 
+0

我會去這個解決方案,而不是我的。它看起來更紅寶石...單行:)。 –

相關問題