How to convert a string or integer to binary in Ruby?

后端 未结 8 1399
栀梦
栀梦 2020-11-30 17:22

How do you create integers 0..9 and math operators + - * / in to binary strings. For example:

 0 = 0000,
 1 = 0001, 
 ...
 9 = 1001

Is the

8条回答
  •  无人及你
    2020-11-30 18:08

    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"}
    

提交回复
热议问题