如何在 Ruby 中将八进制数转换为十进制数? [英] How do I convert an octal number to decimal in Ruby?

查看:65
本文介绍了如何在 Ruby 中将八进制数转换为十进制数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图找到一种使用八进制编号引用数组索引的干净方法.如果我正在寻找八进制 13 的数组索引,它应该返回 a[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

有没有更好的方法?

推荐答案

使用 Ruby 的八进制整数文字语法.在您的数字前放置一个 0,Ruby 会在解析时将其转换为八进制:

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

这篇关于如何在 Ruby 中将八进制数转换为十进制数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆