How do you create integers 0..9 and math operators + - * / in to binary strings. For example:
0 = 0000,
1 = 0001,
...
9 = 1001
Is the
You have Integer#to_s(base)
and String#to_i(base)
available to you.
Integer#to_s(base)
converts a decimal number to a string representing the number in the base specified:
9.to_s(2) #=> "1001"
while the reverse is obtained with String#to_i(base)
:
"1001".to_i(2) #=> 9
Picking up on bta's lookup table idea, you can create the lookup table with a block. Values get generated when they are first accessed and stored for later:
>> lookup_table = Hash.new { |h, i| h[i] = i.to_s(2) }
=> {}
>> lookup_table[1]
=> "1"
>> lookup_table[2]
=> "10"
>> lookup_table[20]
=> "10100"
>> lookup_table[200]
=> "11001000"
>> lookup_table
=> {1=>"1", 200=>"11001000", 2=>"10", 20=>"10100"}