gchubarich
gchubarich

Reputation: 37

Ruby NoMethod Error

I'm trying to solve simple task: find the largest palindrome made from the product of two 3-digit numbers:

def is_palindrome?(number)
  number = number.to_s
  while number.length > 1
    return false if number[0] != number[number.length - 1]
    number = number[1, number.length - 2]
  end
  return true
end

def find_max_palindrome
  x, y, z = 100
  max = 1
  while x < 1000
    while y < 1000
      z = x * y
      max = z if is_palindrome?(z)
      y += 1
    end
    x += 1
  end
  return max
end

puts find_max_palindrome

But something goes wrong:

004.rb:14:in `find_max_palindrome': undefined method `<' for nil:NilClass (NoMethodError)
        from 004.rb:24:in `<main>'

Can anyone tell me where I go wrong?

Upvotes: 0

Views: 49

Answers (2)

spickermann
spickermann

Reputation: 107142

x, y, z = 100

doesn't assign 100 to x, y and z. It only assigns 100 to x. This makes the line while y < 1000 raise an error, because y is still nil.

Change that line to:

x = y = z = 100

Or to the following which I think is easier to read and to understand:

x = 100
y = 100
z = 100

Upvotes: 1

Ursus
Ursus

Reputation: 30071

Watch this one

x, y, z = 100
 => 100 
2.4.0 :002 > x
 => 100 
2.4.0 :003 > y
 => nil 
2.4.0 :004 > z
 => nil 

You mean something like

x = y = z = 100

Upvotes: 1

Related Questions