Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays Fixnum与nil失败回文程序Ruby的比较_Arrays_Ruby_Null_Palindrome_Fixnum - Fatal编程技术网

Arrays Fixnum与nil失败回文程序Ruby的比较

Arrays Fixnum与nil失败回文程序Ruby的比较,arrays,ruby,null,palindrome,fixnum,Arrays,Ruby,Null,Palindrome,Fixnum,我正在为Euler项目中的问题4编写一个程序——在3位数的倍数中找到最大的回文。这是我写的: def palintest(number) num = number.to_s len = num.length if len % 2 != 0 num[(len/2).floor] = '' end if num[0.. (len/2)-1] == num [len/2..len].reverse! return numbe

我正在为Euler项目中的问题4编写一个程序——在3位数的倍数中找到最大的回文。这是我写的:

def palintest(number)
    num = number.to_s
    len = num.length

    if len  % 2 != 0
        num[(len/2).floor] = ''
    end

    if num[0.. (len/2)-1] == num [len/2..len].reverse!
        return number
    end
end

palindromes = []

for i in 100..999
    for j in 100..999
        palindromes << palintest(i*j)
    end
end

puts palindromes.max

我真的搞不清楚到底发生了什么,我已经测试了程序的每个组件,看起来都正常工作。任何帮助都将不胜感激。

乍一看,这是因为当i*j不是回文时,回文测试(i*j)返回零

快速修复:

puts palindromes.reject(&:nil?).max

您将有一堆零添加到数组中。Max不能使用nils-它会比较每个元素。只需添加
回文谢谢,这真的很有帮助!我刚刚开始,所以我忽略了很多简单的事情。
puts palindromes.reject(&:nil?).max
def palindrome?(number)
    num = number.to_s
    len = num.length

    num[(len/2).floor] = '' unless len.even?        

    num[0..(len/2)-1] == num[len/2..len].reverse # return boolean
end

palindromes = []

for i in 100..999
    for j in 100..999
        palindromes << (i * j) if palindrome?(i * j)
    end
end

puts palindromes.max