DEV Community

almokhtar bekkour
almokhtar bekkour

Posted on

1

Check if string is palindrome without String#reverse

def palindrome?(str)
  reversed_str = ''
  i = str.length - 1
  while i >= 0
    reversed_str += str[i]
    i -= 1
  end
  reversed_str == str
end
Enter fullscreen mode Exit fullscreen mode

specs

describe "palindrome?" do
    it "should accept a string as an arg" do
      expect { palindrome?("tot") }.to_not raise_error
    end

    context "when the string is the same forwards and backwards" do
      it "should return true" do
        expect(palindrome?("tot")).to eq(true)
        expect(palindrome?("racecar")).to eq(true)
        expect(palindrome?("madam")).to eq(true)
        expect(palindrome?("aa")).to eq(true)
        expect(palindrome?("a")).to eq(true)
      end
    end

    context "when the string is not the same forwards and backwards" do
      it "should return false" do
        expect(palindrome?("cat")).to eq(false)
        expect(palindrome?("greek")).to eq(false)
        expect(palindrome?("xabcx")).to eq(false)
      end
    end

    it "should not use String#reverse" do
      expect_any_instance_of(String).to_not receive(:reverse)
      palindrome?("tot")
    end
end
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
moopet profile image
Ben Sinclair
Comment hidden by post author

Some comments have been hidden by the post's author - find out more