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

I read the number "98"from the file and tried to convert it to binary using input.to_i(2), but I get 0this 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)}"

Exit:

Input is: 98
Normal way is 0
It works this way 1100010
Calling the number directly works 1100010
+4
source share
1 answer

to_i(2)interprets the expression in the string as a binary number, which should consist only of "0"and "1". Since it is "98"not valid, the result becomes 0the default, by design. (Perhaps it was alternatively intended to return nilor raise the error, but somehow it was designed that way.)

, to_s(2), .

, .. , , . , .., , .

+5

Source: https://habr.com/ru/post/1624304/


All Articles