How do I convert an octal number to decimal in Ruby?

前端 未结 1 1186
一整个雨季
一整个雨季 2021-01-14 04:55

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 <

相关标签:
1条回答
  • 2021-01-14 05:24

    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
    
    0 讨论(0)
提交回复
热议问题