On 18 Jul 2003 18:49:16 GMT
ptkwt / shell1.aracnet.com (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.

------------------------------------------------------------ Fixnum#to_s
     fix.to_s( base=10 ) -> aString
------------------------------------------------------------------------
     Returns a string containing the representation of fix radix base (2
     to 36).
        12345.to_s       #=> "12345"
        12345.to_s(2)    #=> "11000000111001"
        12345.to_s(8)    #=> "30071"
        12345.to_s(10)   #=> "12345"
        12345.to_s(16)   #=> "3039"
        12345.to_s(36)   #=> "9ix"

As others mentioned, '"%b" % n' works too.

>> (0..3).collect { |n| n.to_s(2).split(//).collect { |n| n.to_i } }
=> [[0], [1], [1, 0], [1, 1]]
>> (0..3).collect { |n| ("%02b" % n).split(//).collect { |n| n.to_i } }
=> [[0, 0], [0, 1], [1, 0], [1, 1]]
>> (0..3).collect { |n| ("%02b" % n).split(//).collect { |n| (n.to_i == 0) ? "cat" : "dog" } }
=> [["cat", "cat"], ["cat", "dog"], ["dog", "cat"], ["dog", "dog"]]

Jason Creighton