سؤال

I would like to get the binary literal corresponding from a given integer, in this way:

4.to_literal => 0b100

Is there such to_literal method?

هل كانت مفيدة؟

المحلول

Use to_s with its optional base parameter to get a string.

4.to_s(2) #=> "100"

You can't get a literal as output.

نصائح أخرى

Use String#% or Kernel#sprintf (%#b as format specifier):

'%#b' % 4
# => "0b100"
sprintf('%#b', 4)
# => "0b100"
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top