From: Ammar Ali Date: 2010-07-23T15:08:55+09:00 Subject: Re: Text to Binary On Fri, Jul 23, 2010 at 12:49 AM, Umm Whyshouldisay wrote: > Alright, I think I'm almost there. I've got this: > > test = "Hello World!" > test2 = test.unpack('c*') > test3 = test2.collect {|x| x.to_s(3) + ' '} > puts test3.to_s > > However, I want each number to have 6 digits (6 trits in a tryte). How > would I do that? I want it to, if it didn't already have 6 digits in it, > add the appropriate number of zeros in the beginning of it. Anyone got > any suggestions here? Using the % method of the String class you can pad the value with zeros: '%06d' % 123 #=> 000123 Instead of adding a space to each value inside collect, it is cleaner to do it only on output, using Array#join. test = "Hello World!" decimal = test.unpack('c*') ternary = decimal.collect {|x| x.to_s(3)} puts ternary.map {|v| '%06d' % v }.join(' '); Note that the decimal format specifier 'd' is used in '%06d', even though the value is a String and in ternary. This works because the string is automatically converted to an Integer, and ternary numbers only consist of characters that can pass as decimal numbers. This is OK here since it is for formatting purposes only. GL, Ammar