From: Alphonse 23 Date: 2013-06-01T05:04:07+09:00 Subject: Re: Eloquent Ruby Kaprekar's Number Admin Tensor wrote in post #1110741: > Hi, > > Yes, Kaprekar number is good to be an exercise in creating a (Ruby) > code, but after googling it, what are the practical applications for > Kaprekar numbers? > There isn't any, I believe. Though there could be a use for them in the future. I used Kaprekar's number because it's simple. This was just an exercise in writing ruby code, specifically how to write good readable "eloquent" code. Peter Hickman wrote in post #1110774: > You never use ks as it is you always use ks.to_s so we might was well go > with that and make is easier to read. > The line breaks make it more obvious as to the steps you are taking. > > Again it is just a personal preference. > > Finally the simple_test code does not work for failures. Woops, sorry about that. Yes, the simple_test code is really bad. I'm still learning how to use Rspec. After reviewing everyone else's algorithms here's my new version. I believe this is the most readable and rubyist like. def kaprekar?(num) return false if num.zero? num_square = (num**2).to_s num_len = num_square.length midpoint = (num_len / 2)-1 left = num_square[0..midpoint].to_i right = num_square[midpoint+1..-1].to_i num == left + right end p kaprekar?(9) p kaprekar?(297) Now I need to go learn Rspec.. -- Posted via http://www.ruby-forum.com/.