So just messing around with a problem on project_euler I wanted to write a simple method for checking if an integer was a palindrome. The most important lesson that I learned from this is that I could take and integer, convert it to a string, reverse the string, and THEN convert it back into an integer! A pretty nifty trick about converting between classes that I think will be very handy in the future. From here I am now trying to see the highest palindrome integer multiplied by 2 three digit numbers so I will have to write a method that that loops while multiplying different combinations of three digit numbers while calling the is_palindrome? method in order to see what the highest number is. More to come...I'm starting to feel less afraid of the fundamentals and embrace them more and more with each exercise that I complete. Time to let go and get away from the shallow end of the pool...
def is_palindrome?(result) if result == result.to_s.reverse.to_i return true else return false end end
Well done -- concise check.
ReplyDeleteFun thing about ruby is that it has implicit returns -- meaning it will return the value of the last comparison/object. This means you could shorten your already short code to:
def is_palindrome?(result)
result == result.to_s.reverse.to_i
end
Ruby will compare result and the reversed result, decide it's true, then see it's the last thing in the block and return that true/false value.
Great advice Mike. Thanks for the tip! Refactor, Refactor, Refactor ;-).
ReplyDelete