egyamado
egyamado

Reputation: 1131

How can I check for first letter(s) in string in Ruby?

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".

Upvotes: 1

Views: 12612

Answers (7)

Gonzalo Franco
Gonzalo Franco

Reputation: 1

Figured I'd share my first contribution! Good luck!

def method(word)
  word[0].eql?("A" || "E" || "I" || "O" || "U")
end

Upvotes: 0

MurifoX
MurifoX

Reputation: 15109

Looks like you are removing the first character if the word starts with a consonant too, so:

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

Upvotes: 1

tigeravatar
tigeravatar

Reputation: 26670

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"

Upvotes: 1

Vamsi Krishna
Vamsi Krishna

Reputation: 3792

The below piece of code passes all the tests...

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

Upvotes: 0

Gluz
Gluz

Reputation: 3264

Your code means: if word start with ('a','e','i','o','u') add "ay" at the end else add "bay" at the end.

Second test will be "bananabay" and not "ananabay" (with b as first letter)

Upvotes: 1

Pierre-Louis Gottfrois
Pierre-Louis Gottfrois

Reputation: 17631

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.

Upvotes: 5

Rajarshi Das
Rajarshi Das

Reputation: 12350

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

Upvotes: 1

Related Questions