I had a pleasure of getting an interview with an upcoming startup (i won’t disclose which one). Besides implementing fizz buzz in ruby, i was asked to write a method that would check for input to be a palindrome.
Palindrome is a word, phrase, number, or other sequence of symbols or elements, whose meaning may be interpreted the same way in either forward or backward.
Keep in mind: using reverse is not allowed 🙂
I wrote two versions since i wasn’t pleased with my first one.
Rspec – testing driven development
require 'spec_helper' require 'blah' describe "Blah" do it "should match reversed order of the word " do palindrome("abba").should == true palindrome("abcba").should == true end it "should reject if reversed order doesnt match" do palindrome("abbac").should_not == true end it "should handle empty string with passing" do palindrome("").should == true end it "should handle various cases " do palindrome("AbbA").should == true end it "should handle empty spaces " do palindrome(" Ab bA").should == true end end
Version 1
def palindrome2(word) i = 0 last = -1 word.each_char do |c| if word[i] != word[last] return false end i+=1 last -=1 end return true end
Version 2
def palindrome(word) word = word.downcase.gsub(" ","").chars word.each{|c| return false if word.shift != word.pop } true end
I have a feeling there is a better way of writing this.
Thanks