0

显然,散列不适用于这种测试。无论如何,这是我到目前为止所拥有的:

module Enumerable
  def palindrome?
    arr = []
    self.reverse_each do |x|
      arr << x
    end
    self == arr
  end
end

我的另一个想法是使用 for 循环逐个元素地循环遍历 arr 和 self 元素以进行检查。

4

2 回答 2

2
x = 'Tiger'
p "#{x} is planidrome" if x ==  x.reverse #=> no ouput
x = 'RADAR'
p "#{x} is planidrome" if x ==  x.reverse #=> "RADAR is planidrome"

module Enumerable
  def palindrome?
    p  self.to_a ==  self.to_a.reverse
  end
end
['r','a','d','a','r'].palindrome? #=> true
于 2013-04-07T04:00:41.767 回答
2
module Enumerable
  def palindrome?
    a = to_a
    a == a.reverse
  end
end
于 2013-04-07T04:36:51.743 回答