Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need `to_s` on top of `to_i` when reading from a file?

Tags:

string

ruby

I read a number "98" from a file, and tried to convert it to binary using input.to_i(2), but I get 0 that way.

input=File.read("input.dat")
puts "Input is: #{input}"
puts "Normal way is #{input.to_i(2)}"
puts "It works this way #{input.to_i.to_s(2)}"
puts "Calling the number directly works #{98.to_s(2)}"

Output is:

Input is: 98
Normal way is 0
It works this way 1100010
Calling the number directly works 1100010
like image 530
mateo_io Avatar asked Jan 14 '16 15:01

mateo_io


1 Answers

to_i(2) interprets an expression in a string as a binary number, which should only consist of "0" and "1". Since "98" is invalid, the result becomes 0 by default, by design. (It could have been alternatively designed to return nil or raise an error, but somehow it is designed this way.)

To display a number as binary, you need to_s(2) because that gives the expression of the number in binary.

As a number, there is no distinction between binary number, decimal number etc. All there is is a number. What those notions with binary, decimal, etc. are about is the way they are expressed as a string.

like image 167
sawa Avatar answered Nov 02 '22 16:11

sawa