From: "Mauricio Fernández" Date: 2003-07-19T04:36:23+09:00 Subject: Re: [SNIPPET] Binary counter On Sat, Jul 19, 2003 at 04:05:39AM +0900, Phil Tomson wrote: > I needed to test a class which had a certain number of 'binary' inputs (ie. each input > takes either 0 or 1 (or false or true) ). In order to do this I needed to try out every > possible combination of inputs - essentially a binary count, like: > > 0,0,0,0 > 0,0,0,1 > .... > 1,1,1,0 > 1,1,1,1 > > I figured I could just increment an integer and, then convert it to binary, but: > 1) there doesn't seem to be a builtin to_bin method on FixNum. > 2) I'd still have to deal with indexing, etc. > (OK, it wouldn't be that hard to implement #1 and #2 is not that hard either, but I > decided to go a different route for fun ;-) >> 8.times {|i| 4.times {|j| print i[3-j]}; puts } 0000 0001 0010 0011 0100 0101 0110 0111 => 8 >> class Fixnum; def to_bin(bits=31); a = []; bits.times{|i| a.unshift self[i]}; a end end => nil >> 10.times {|i| p i.to_bin(4)} [0, 0, 0, 0] [0, 0, 0, 1] [0, 0, 1, 0] [0, 0, 1, 1] [0, 1, 0, 0] [0, 1, 0, 1] [0, 1, 1, 0] [0, 1, 1, 1] [1, 0, 0, 0] [1, 0, 0, 1] -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Q: What's the big deal about rm, I have been deleting stuff for years? And never lost anything.. oops! A: ... -- From the Frequently Unasked Questions