Last Updated: February 25, 2016
·
1.561K
· kgrz

Getting binary representations in Ruby

If you wanted to get a binary representation of a string in Ruby, you can do:

"Hi! I'm a string".chars.map(&:ord).map { |x| x.to_s(2) }

The optional argument in #to_s takes a number using which the number is formatted.

10.to_s         # => "10"      (base-10)
10.to_s(2)     # => "1010"  (binary)
10.to_s(16)   # =>  "a"        (hexadecimal)