How do i just enter octal value or binary value to print in ruby as Integer i tried that an it works but is there any other way?
puts '1011'.to_i(2) # => 11
How do i just enter octal value or binary value to print in ruby as Integer i tried that an it works but is there any other way?
puts '1011'.to_i(2) # => 11
A few ways. You can either prepend your number with radix indicators (where 0= octal or 0b = binary):
01011
#=> 521
0b1011
#=> 11
...or you can use Integer() to either prepend those radix indicators to a string...
number = '1011'
Integer("0#{number}")
#=> 521
Integer("0b#{number}")
#=> 11
...or to supply the desired base as a a second argument:
Integer('1011', 8)
#=> 521
Integer('1011', 2)
#=> 11
There's also the oct method for converting string to octal but I don't believe it has a binary counterpart:
'1011'.oct
#=> 521
try this
# Binary to Integer
# puts 0b(binary)
puts 0b1011 => 11
puts 0b1011.class => Integer
# Octal to Integer
# puts (octal_value)
puts 0366 => 246
puts 0b1011.class => Integer
# Hex to Integer
# puts 0x(hex value)
puts 0xff => 255
puts 0xff.class => Integer