From: Ch Skilbeck Date: 2006-08-08T07:44:05+09:00 Subject: Re: nextPowerOf2(n) Ch Skilbeck wrote: > Hi, > > Can someone tell me if there's a better way to do this? It takes a > number and returns the next power of 2 up (or the original if it was > already a power of 2) Specifically, are there features of Ruby that I > should be using in this case? > > Cheers, > Charlie. > > def nextPowerOf2(n) > raise "integer please" if !n.kind_of? Integer > high = 0 > count = 0 > (0..n.size * 8 - 2).each {|b| count += n[b] ; high = b if n[b] != 0} > 1 << high + (count > 1 ? 1 : 0) > end Thankyou all - very helpful indeed. In my eagerness to use Ruby features I managed to almost completely forget how to code and write something that's orders of magnitude slower than it needed to be. This has been extremely useful - I'm totally digging this Ruby deal, it feels like a comfortable holiday home with nice weather and a good beach. -- Posted via http://www.ruby-forum.com/.