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

ACI image

ACI.dev: Best Open-Source Composio Alternative (AI Agent Tooling)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Star our GitHub!

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

Image of Timescale

PostgreSQL for Agentic AI — Build Autonomous Apps on One Stack ☝️

pgai turns PostgreSQL into an AI-native database for building RAG pipelines and intelligent agents. Run vector search, embeddings, and LLMs—all in SQL

Build Today

👋 Kindness is contagious

Explore this compelling article, highly praised by the collaborative DEV Community. All developers, whether just starting out or already experienced, are invited to share insights and grow our collective expertise.

A quick “thank you” can lift someone’s spirits—drop your kudos in the comments!

On DEV, sharing experiences sparks innovation and strengthens our connections. If this post resonated with you, a brief note of appreciation goes a long way.

Get Started