Let's say I need to make integers 0..9 and math operators + - * / binary strings. So 0 = 0000, 1 = 0001, etc.. Is there a way to do this with Ruby 1.8.6 without using a library?
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 Integer#to_s(base)
:
"1001".to_i(2) #=> 9
If you're only working with the single digits 0-9, it's likely faster to build a lookup table so you don't have to call the conversion functions every time.
lookup_table = Hash.new
(0..9).each {|x|
lookup_table[x] = x.to_s(2)
lookup_table[x.to_s] = x.to_s(2)
}
lookup_table[5]
=> "101"
lookup_table["8"]
=> "1000"
Indexing into this hash table using either the integer or string representation of a number will yield its binary representation as a string.
If you require the binary strings to be a certain number of digits long (keep leading zeroes), then change x.to_s(2)
to sprintf "%04b", x
(where 4
is the minimum number of digits to use).
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"}