2013-04-07 43 views
0

顯然,哈希不適用於這種測試。不管怎麼說,這是我到目前爲止有:如何檢查一個適當的枚舉是否是迴文

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

另一個想法我是循環ARR和自我逐個元素與一個for循環來檢查。

+0

這是任何機會,一門功課的問題嗎? – Jason 2013-04-07 16:09:04

回答

2
module Enumerable 
    def palindrome? 
    a = to_a 
    a == a.reverse 
    end 
end 
+0

超級簡單,謝謝! – Rishi 2013-04-07 04:40:39

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 
+0

這是用於字符串,而不是枚舉類型。 – Rishi 2013-04-07 04:31:33

+0

@ user1796994看我編輯 – 2013-04-07 04:45:36