From: "David A. Black" Date: 2009-08-10T03:32:46+09:00 Subject: Re: Generate binary sequences of length n? Hi -- On Mon, 10 Aug 2009, Tom Best wrote: > I'm rather new to Ruby. I feel this should be very simple, but I'm > having trouble: > > I'd like to write a script to work through all possible binary sequences > of length n. > > > > The script would work as follows: > > mylength = 4 > resultz = binary_seq_generator(mylength) > puts "#{resultz}" > > #resultz, not necessarily in this order: > ["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"] Try this: def binary_seq_generator(n) (0...(1 << n)).map {|e| "%0#{n}d" % e.to_s(2) } end Doesn't necessarily roll off the fingers as readily as some Ruby idioms do :-) But I think all or most of what you need is there, and there are some interesting bits to it. David -- David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com Q: What's the best way to get a really solid knowledge of Ruby? A: Come to our Ruby training in Edison, New Jersey, September 14-17! Instructors: David A. Black and Erik Kastner More info and registration: http://rubyurl.com/vmzN