How to convert octal to decimal in Ruby?

I am trying to find a clean way to reference an array index using octal numbering. If I look for the index of an array that is octal 13, it should return a value for a[11].

This is what I came up with to accomplish this, but it does not seem very elegant or efficient:

a = [ 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62 ]

v = 13

puts a[v.to_s.to_i(8)]  # => 61
 # OR
puts a[v.to_s.oct]      # => 61

Is there a better way?

+3
source share
1 answer

Use Ruby eighth integer syntax. Put 0 in front of your number, and Ruby will convert it to octal when parsing:

v = 013 # => 11
a[v]    # => 61

, , , , :

number = gets.chomp # => "13"
v = number.to_i(8)  # => 11
a[v]                # => 61
+6

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


All Articles