How do I convert an octal number to decimal in Rub

2020-03-26 00:11发布

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

This is what I have come up with to accomplish it, but it doesn't 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?

标签: ruby octal
1条回答
在下西门庆
2楼-- · 2020-03-26 00:36

Use Ruby's octal integer literal syntax. Place a 0 before your number, and Ruby will convert it to octal while parsing:

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

If the octal number is coming from an outside source like a file, then it is already a string and you'll have to convert it just like you did in your example:

number = gets.chomp # => "13"
v = number.to_i(8)  # => 11
a[v]                # => 61
查看更多
登录 后发表回答