From: Phil Tomson Date: 2006-06-04T06:35:24+09:00 Subject: Re: Where can one find examples of masterful Ruby code? On 6/3/06, Alder Green wrote: > > For example: check if integer i is a power of 2, with an expression no > more than 13 characters long. > > Solution: (i & (i - 1)) > > Note that this solution is not only very concise, but also (on any > reasonable implementation) very fast. Masterful code has a tendency to > be "correct" in many ways. > Thanks for this very useful snippet. It was worth reading the thread for. Probably should be methodized as: def powerof2?( i ) (i & (i - 1))==0 end Of course it's not immediately obvious from reading the code how it works till you try an example: 1000 #8 in binary 0111 #7 in binary &---------- 0000 ...so maybe readability isn't always part of the criteria for 'masterful' code. I do think that the way you've done it is the fastest way to figure out if an integer is a power of 2 and after you work through an example it does seem quite elegant. Phil