1

I'm writing test file, but I can't get it pass second test, here:

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

Is start_with? the right method to do the job?

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

EDIT: My solution is not complete. My code pass first test only because I was able to push "ay" to the end of word. What I'm missing to pass the second test is to remove the first letter if its consonant, which is "b" in "banana".

4

7 回答 7

5

You can do this also:

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

Using a Regex might be overkill in your case, but could be handy if you want to match more complex strings.

于 2013-08-27T11:09:54.267 回答
1

您的代码意味着:如果单词以 ('a','e','i','o','u') 开头,则在末尾添加“ay”,否则在末尾添加“bay”。

第二个测试将是“bananabay”而不是“ananabay”(第一个字母为 b)

于 2013-08-27T11:16:44.390 回答
1

如果单词也以辅音开头,则看起来您正在删除第一个字符,因此:

if word.start_with?('a','e','i','o','u')
  word[0] = ''
  word << 'ay'
else 
  consonant = word[0]
  word << "#{consonant}ay"
end
于 2013-08-27T11:13:46.943 回答
1

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

于 2013-08-27T11:14:18.493 回答
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"
于 2013-08-27T15:17:42.813 回答
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
于 2013-08-27T14:01:25.873 回答
0

想我会分享我的第一个贡献!祝你好运!

def method(word)
  word[0].eql?("A" || "E" || "I" || "O" || "U")
end
于 2020-07-25T12:31:53.920 回答