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

后端 未结 8 1401
栀梦
栀梦 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 17:45

    In ruby Integer class, to_s is defined to receive non required argument radix called base, pass 2 if you want to receive binary representation of a string.

    Here is a link for an official documentation of String#to_s

      1.upto(10).each { |n|  puts n.to_s(2) }
    

提交回复
热议问题