From: sto.mar@... Date: 2013-05-31T18:34:20+09:00 Subject: Re: Eloquent Ruby Kaprekar's Number Am 31.05.2013 01:59, schrieb Alphonse 23: > Which way is the eloquent ruby way to write this algorithm? > > Kaprekar Number > > 9 is a Kaprekar number since > 9 ^ 2 = 81 and 8 + 1 = 9 > > 297 is also Kaprekar number since > 297 ^ 2 = 88209 and 88 + 209 = 297. > > In short, for a Kaprekar number k with n-digits, if you square it and > add the right n digits to the left n or n-1 digits, the resultant sum is > k. > > !Spoiler Below! > > # way one > def kaprekar?(k) > ks = k**2 > lenf = (ks.to_s.length)-1 > lenh = (ks.to_s.length / 2) - 1 > a = ks.to_s[0..lenh].to_i > b = ks.to_s[lenh+1..lenf].to_i > k == (a+b) > end > > # way two > def kaprekar?(k) > a = (k**2).to_s[0..((((k**2).to_s.length) / 2) - 1)].to_i > b = (k**2).to_s[(((((k**2).to_s.length) / 2) - > 1)+1)..(((k**2).to_s.length)-1)].to_i > k == (a+b) > end > > # way three > def kaprekar?(k) > k == ((k**2).to_s[0..((((k**2).to_s.length) / 2) - > 1)].to_i)+((k**2).to_s[(((((k**2).to_s.length) / 2) - > 1)+1)..(((k**2).to_s.length)-1)].to_i) > end > > def simple_test(i) > if kaprekar?(i) == true then p "success on #{i}" else "fail on #{i}" > end > end > > simple_test(9) > simple_test(297) > > All three pass my tests, but which of the three would be considered the > most eloquent written ruby way? As in, which would be consider best > style-wise? The first takes up the most lines, but uses less nesting. > The last uses only one line but uses lots of nesting. To me, as long as there are no performance considerations involved, generally the best version is the one I understand in the shortest amount of time. Cryptic one-liners might be nice as brain-teasers but not for real applications. Also, I highly prefer telling variable names over ks, a, b, etc. Why not use square, digits, left_number, ... or similar? IMO that make a big difference in readability. --