如何在 Ruby 中将八进制数转换为十进制数?
我试图找到一种使用八进制编号引用数组索引的干净方法。如果我正在查找八进制 13 的数组索引,它应该返回 a[11]
的值。
这就是我想出的方法来完成它,但它看起来不是很优雅或有效:
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
有更好的方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 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:
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: