ruby on rails strings Ruby way to Check for string palindrome




strings in ruby (6)

I wanted to check if a string is palindrome or not using ruby code.

I am a starter in ruby so not too aquainted with the string methods in ruby


str= gets.chomp 
str_rev=""
n=1
while str.length >=n
    str_rev+=str[-n]
    n+=1
end

if str_rev==str
    puts "YES"
else
    puts "NO"
end

class String
  def palindrome?
    self.downcase == self.reverse.downcase
  end
end

puts "racecar".palindrome? # true
puts "Racecar".palindrome? # true 
puts "mississippi".palindrome? # false 

def check_palindromic(variable)
  if variable.reverse == variable #Check if string same when reversed 
    puts "#{ variable } is a palindrome."
  else # If string is not the same when reversed
    puts "#{ variable } is not a palindrome."
  end
end

The recursive solution shows how strings can be indexed in Ruby:

def palindrome?(string)
  if string.length == 1 || string.length == 0
    true
  else
    if string[0] == string[-1]
      palindrome?(string[1..-2])
    else
      false
    end
  end
end

If reading the Ruby string documentation is too boring for you, try playing around with the Ruby practice questions on CodeQuizzes and you will pick up most of the important methods.


If you are not acquainted with Ruby's String methods, you should have a look at the documentation, it's very good. Mithun's answer already showed you the basic principle, but since you are new to Ruby, there's a couple more things to keep in mind:

*) If you have a predicate method, it's customary to name it with a trailing question mark, e.g. palindrome?.

*) Boolean expressions evaluate to a boolean, so you don't need to explicitly return true or false. Hence a short idiomatic version would be

def palindrome?(str)
  str == str.reverse
end

*) Since Ruby's classes are open, you could add this to the string class:

class String
  def palindrome?
    self == self.reverse
  end
end

*) If you don't want to monkey-patch String, you can directly define the method on single object (or use a module and Object#extend):

foo = "racecar"
def foo.palindrome?
  self == self.reverse
end

*) You might want to make the palindrome check a bit more complex, e.g. when it comes to case or whitespace, so you are also able to detect palindromic sentences, capitalized words like "Racecar" etc.

pal = "Never a foot too far, even."
class String
  def palindrome?
    letters = self.downcase.scan(/\w/)
    letters == letters.reverse
  end
end
pal.palindrome? #=> true

> first method
a= "malayalam"
  if a == a.reverse
    puts "a is true"
  else
    puts "false"
  end

> second one
a= "malayalam"
a=a.split("")
i=0
ans=[]
  a.count.times do
    i=i+1
      k=a[-(i)]
      ans << k
    end
  if a== ans
      puts "true"
  else
      puts "false"
  end





ruby-on-rails-3